在我的方法中,我将数据从文件保存到输出流。
现在看起来像这样
public void readFileToOutputStream(Path path, OutputStream os) {
byte[] barr = Files.readAllBytes(path)
os.write(barr);
os.flush();
}
但是在这个解决方案中,所有字节都加载到内存中,我想使用缓冲区来释放其中的一些字节。
我可以用什么来为我的读数提供缓冲区?
最佳答案
最简单的方法是使用 Commons IO library
public void readFileToOutputStream(Path path, OutputStream os) throws IOException { try(InputStream in = new FileInputStream(path.toFile())){ IOUtils.copy(in, os); } }
您可以自行实现类似于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); } } }
关于java - 将 byte[] 写入 OutputStream 时添加缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37408022/