将数据输入转换为数据输入流?

发布于 2024-12-06 14:17:35 字数 58 浏览 0 评论 0原文

java中如何将DataInput转换为DataInputStream? 我需要知道数据输入的大小。

How can I convert DataInput to DataInputStream in java?
I need to know the size of the DataInput.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

乖乖 2024-12-13 14:17:35

由于根据定义,流实际上没有开始或结束,因此没有万无一失的方法来知道有多少可用,因此您只需以固定大小的块从流中读取。听起来你最好使用普通的旧 .read() 而不是 readFully():

    DataInputStream dis = new DataInputStream(...);
    byte[] buf = new byte[1024];
    int lastRead = 0;

    do {
        lastRead = dis.read(buf);
        //do something with 'buf' here

    } while (lastRead > 0);

Since a stream, by definition, really has no begining or end and thus no fool proof way of knowing how much is available, you just have to read from the stream in fixed sized chunks. It almost sounds like you'd be better off with plain old .read() rather than readFully():

    DataInputStream dis = new DataInputStream(...);
    byte[] buf = new byte[1024];
    int lastRead = 0;

    do {
        lastRead = dis.read(buf);
        //do something with 'buf' here

    } while (lastRead > 0);
番薯 2024-12-13 14:17:35

当您想知道要读取多少字节时,您会遇到困难。最简单的解决方案是将其转换为 ByteArrayInputStream 并使用它的 available() 方法来了解有多少字节可供读取。

以下示例对我有用

DataInput in = (...);
ByteArrayInputStream bis = (ByteArrayInputStream) in;
byte[] buffer = new byte[bis.available()];
in.readFully(buffer);
//use buffer as your wish

You'll encounter difficulty when you want know how many bytes to be read. Simplest solution is to cast it to a ByteArrayInputStream and use it's available() method to get to know how many bytes are available for reading.

Following example worked for me

DataInput in = (...);
ByteArrayInputStream bis = (ByteArrayInputStream) in;
byte[] buffer = new byte[bis.available()];
in.readFully(buffer);
//use buffer as your wish
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文