java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java InputStream获取字节大小

java中InputStream获取字节大小相关方法详解

作者:海ou

这篇文章主要给大家介绍了关于java中InputStream获取字节大小相关方法的相关资料,在Java中要实现读取文件大小,可以使用InputStream来读取文件的内容,并通过获取读取的字节数来得到文件的大小,需要的朋友可以参考下

1 通过StreamUtils工具类的copyToByteArray()方法获取(推荐)

正常大部分项目都是使用的Spring,而Spring已经帮我们开发好了相应的工具类,我们直接调用即可。

InputStream is = this.getClass().getResourceAsStream(filePath);
byte[] bytes = StreamUtils.copyToByteArray(is);
is.read(bytes);

2 通过available()方法获取(不推荐)

InputStream is = this.getClass().getResourceAsStream(filePath);
byte[] bytes = new byte[is.available()];
is.read(bytes);

2.1 不推荐理由

可以看一下方法注释:

/**
 * 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.
 *
 * <p> Note that while some implementations of {@code 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.
 *
 * <p> A subclass' implementation of this method may choose to throw an
 * {@link java.io.IOException} if this input stream has been closed by
 * invoking the {@link #close()} method.
 *
 * <p> The {@code available} method for class {@code InputStream} always
 * returns {@code 0}.
 *
 * <p> This method should be overridden by subclasses.
 *
 * @return     an estimate of the number of bytes that can be read (or skipped
 *             over) from this input stream without blocking or {@code 0} when
 *             it reaches the end of the input stream.
 * @exception java.io.IOException if an I/O error occurs.
 */

大致意思是返回的字节数可能由于网络原因阻塞一次只能返回部分字节或者另外一个线程也读了导致返回部分字节,也就是说如果使用available()方法去获取InputStream的长度来作为字节数组的长度,那可能会出现字节接受不完整的错误,所以不推荐使用该方法的返回值去分配一个缓冲的byte数组。

3 通过file.length()来获取

File file = new File(path);
InputStream stream = new FileInputStream(file);
byte[] bytes = new byte[file.length()]

总结 

到此这篇关于java中InputStream获取字节大小相关方法的文章就介绍到这了,更多相关java InputStream获取字节大小内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文