将 byte[] 写入 OutputStream 时添加缓冲区

Adding buffer when writing byte[] to OutputStream

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

目前看来是这样

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

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

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

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

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

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();
}

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

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
                        }
                    }
                }
            }
        }
    }
}

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

  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);
        }
      }
    }