开发者

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

开发者 https://www.devze.com 2023-11-19 11:23 出处:网络 作者: 海ou
目录1 通过StreamUtils工具类的copyToByteArray()方法获取(推荐)2 通过available()方法获取(python不推荐)2.1 不推荐理由3 通过file.length()来获取总结 1 通过StreamUtils工具类的copyToByteArray()方法获
目录
  • 1 通过StreamUtils工具类的copyToByteArray()方法获取(推荐)
  • 2 通过available()方法获取(python不推荐)
    • 2.1 不推荐理由
  • 3 通过file.length()来获取
    • 总结 

      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 numandroidber of bytes in the stream, many will not.  It is
       * never correct to use the return v编程客栈alue 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.IOExceptphpion} 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 bytepythons 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获取字节大小内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

      0

      精彩评论

      暂无评论...
      验证码 换一张
      取 消

      关注公众号