Java InputStream读取问题 [英] Java InputStream reading problem

查看:164
本文介绍了Java InputStream读取问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java类,我通过InputStream读取数据

I have a Java class, where I'm reading data in via an InputStream

    byte[] b = null;
    try {
        b = new byte[in.available()];
        in.read(b);
    } catch (IOException e) {
        e.printStackTrace();
    }

当我从IDE(Eclipse)运行我的应用程序时它非常有效。

It works perfectly when I run my app from the IDE (Eclipse).

但是当我导出我的项目并将其打包在JAR中时,read命令不会读取所有数据。我怎么能修复它?

But when I export my project and it's packed in a JAR, the read command doesn't read all the data. How could I fix it?

当InputStream是一个文件(~10kb)时,这个问题主要发生。

This problem mostly occurs when the InputStream is a File (~10kb).

谢谢!

推荐答案

通常我更喜欢在从输入流中读取时使用固定大小的缓冲区。正如evilone指出的那样,使用available()作为缓冲区大小可能不是一个好主意,因为,例如,如果您正在读取远程资源,那么您可能事先不知道可用字节。您可以阅读的javadoc InputStream 可以获得更多洞察力。

Usually I prefer using a fixed size buffer when reading from input stream. As evilone pointed out, using available() as buffer size might not be a good idea because, say, if you are reading a remote resource, then you might not know the available bytes in advance. You can read the javadoc of InputStream to get more insight.

以下是我通常用于读取输入流的代码片段:

Here is the code snippet I usually use for reading input stream:

byte[] buffer = new byte[BUFFER_SIZE];

int bytesRead = 0;
while ((bytesRead = in.read(buffer)) >= 0){
  for (int i = 0; i < bytesRead; i++){
     //Do whatever you need with the bytes here
  }
}

read()的版本我在这里使用将尽可能多地填充给定的缓冲区并且
返回实际读取的字节数。这意味着您的缓冲区可能包含尾随垃圾数据,因此使用最多 bytesRead 的字节非常重要。

The version of read() I'm using here will fill the given buffer as much as possible and return number of bytes actually read. This means there is chance that your buffer may contain trailing garbage data, so it is very important to use bytes only up to bytesRead.

注意行(bytesRead = in.read(buffer))> = 0 InputStream规范中没有任何内容表示read( )无法读取0个字节。根据您的情况,当read()根据特殊情况读取0个字节时,您可能需要处理这种情况。对于本地文件,我从未遇到过这种情况;但是,当读取远程资源时,我实际上看到read()不断读取0个字节,导致上面的代码进入无限循环。我通过计算读取0字节的次数来解决无限循环问题,当计数器超过阈值时,我将抛出异常。您可能不会遇到此问题,但请记住这一点:)

Note the line (bytesRead = in.read(buffer)) >= 0, there is nothing in the InputStream spec saying that read() cannot read 0 bytes. You may need to handle the case when read() reads 0 bytes as special case depending on your case. For local file I never experienced such case; however, when reading remote resources, I actually seen read() reads 0 bytes constantly resulting the above code into an infinite loop. I solved the infinite loop problem by counting the number of times I read 0 bytes, when the counter exceed a threshold I will throw exception. You may not encounter this problem, but just keep this in mind :)

出于性能原因,我可能会远离为每次读取创建新的字节数组。

I probably will stay away from creating new byte array for each read for performance reasons.

这篇关于Java InputStream读取问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆