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 不推荐理由
可以看一下方法注释:文章来源:https://www.toymoban.com/news/detail-726585.html
/** * 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数组。文章来源地址https://www.toymoban.com/news/detail-726585.html
3 通过file.length()来获取
File file = new File(path);
InputStream stream = new FileInputStream(file);
byte[] bytes = new byte[file.length()]
到了这里,关于java的InputStream获取字节大小相关方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!