【问题标题】:Adding buffer when writing byte[] to OutputStream [duplicate]将字节 [] 写入 OutputStream 时添加缓冲区 [重复]
【发布时间】:2016-09-21 08:08:40
【问题描述】:

在我的方法中,我将数据从文件保存到输出流。

目前看起来是这样的

public void readFileToOutputStream(Path path, OutputStream os) {
    byte[] barr = Files.readAllBytes(path)

    os.write(barr);
    os.flush();
}

但是在这个解决方案中,所有字节都加载到内存中,我想使用缓冲区来释放其中的一些。

我可以用什么来为我的读数提供缓冲区?

【问题讨论】:

标签: java buffer


【解决方案1】:
  1. 最简单的方法是使用Commons IO library

    public void readFileToOutputStream(Path path, OutputStream os) throws IOException {
      try(InputStream in = new FileInputStream(path.toFile())){
        IOUtils.copy(in, os);
      }
    }
    
  2. 你可以自己实现类似于IOUtils.copy

    public void readFileToOutputStream(Path path, OutputStream os) throws IOException {
      try (InputStream fis = new FileInputStream(path.toFile());
           InputStream bis = new BufferedInputStream(fis)) {
        byte[] buffer = new byte[4096];
        int n;
        while ((n = bis.read(buffer)) >= 0) {
          os.write(buffer, 0, n);
        }
      }
    }
    

【讨论】:

    【解决方案2】:

    如果我理解你的问题,你只想将指定数量的字节写入内存?

    outputstreams write 方法也可以从一个起始偏移量和长度开始写入一个指定的字节数组。

    https://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html

    public void readFileToOutputStream(Path path, OutputStream os, int off, int len) {
        byte[] barr = Files.readAllBytes(path)
    
        os.write(barr, off, len);
        os.flush();
    }
    

    【讨论】:

      【解决方案3】:

      使用缓冲流为您管理缓冲区:

      public void readFileToOutputStream(Path path, OutputStream os) {
          try (FileInputStream fis = new FileInputStream(path.toFile())) {
              try (BufferedInputStream bis = new BufferedInputStream(fis)) {
                  try (DataInputStream dis = new DataInputStream(bis)) {
                      try (BufferedOutputStream bos = new BufferedOutputStream(os)) {
                          try (DataOutputStream dos = new DataOutputStream(bos)) {
                              try {
                                  while (true) {
                                      dos.writeByte(dis.readByte());
                                  }
                              } catch (EOFException e) {
                                  // normal behaviour
                              }
                          }
                      }
                  }
              }
          }
      }
      

      【讨论】:

      • 您可以在try 部分内拥有多个资源,而不是嵌套与资源一样多的try 块。
      • @Tunaki 不知道这一点。谢谢
      【解决方案4】:

      使用FileInputStream::read(byte[] b, int off, int len)link 最多读取 len 字节到缓冲区 b 和 FileOutputStream::write(byte[] b, int off, int len) link2 从缓冲区写入

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-22
        • 1970-01-01
        • 2018-05-15
        • 1970-01-01
        • 2017-09-29
        • 1970-01-01
        相关资源
        最近更新 更多