首页 > 输入流读取数据

输入流读取数据

public static byte[] readAsByteArray(InputStream input) throws IOException {
    byte[] bytes = new byte[input.available()];
    try{
        input.read(bytes);
    }catch(IOException e){
        System.out.println("ERROR");
    }
    return bytes;
}

大家看下这样读取输入流的数据对不对,和其它IO流的使用方式比较 有什么不足的地方?
欢迎大家给出意见


byte[] bytes=new byte[input.available]创建的缓冲区可能超过内存大小


小文件还好,大文件当心内存问题呀


你这样写,缓冲器可能超过内存大小,如果流很大的话。


谢邀!

这样读流是完全错误的!
参考available()方法的API文档:http://docs.oracle.com/javase...

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.
Note that while some implementations of InputStream will return the total number of bytes in the stream, many will not. It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream.

上面加粗的这句话的意思是:一部分InputStream的实现类会返回整个流的字节数,而一部分并不是

其中FileInputStream的available()方法返回的就不一定是这个文件的总大小(不信你找个8G的大文件试试)。所以想获取文件大小要用File.length()方法,一定不要用FileInputStream的available()。

另外,很多InputStream是阻塞的(也就是BIO/NIO中的BIO),例如各种网络编程相关的InputStream,在网速不好,或者另一方没有传数据过来的时候,read是阻塞的,available()返回的是0,但是并不代表InputStream已经读完了,而是InputStream正在阻塞等待数据过来。

如果你真想把一个InputStream的所有数据读到一个byte数组中,推荐使用commons-io的IOUtils:

byte[] byteArray = IOUtils.toByteArray(inputStream);

当然,如果InputStream中的数据太大,一股脑加载到内存中,很可能会Out of memory。

【热门文章】
【热门文章】