首页 > 基础资料 博客日记

java的InputStream获取字节大小相关方法

2023-11-10 17:58:46基础资料围观228

Java资料网推荐java的InputStream获取字节大小相关方法这篇文章给大家,欢迎收藏Java资料网享受知识的乐趣

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()]


文章来源:https://blog.csdn.net/weixin_48469176/article/details/132426400
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云