在我的方法中,我将数据从文件保存到输出流。
现在看来
public void readFileToOutputStream(Path path, OutputStream os) {
byte[] barr = Files.readAllBytes(path)
os.write(barr);
os.flush();
}
但是在此解决方案中,所有字节均加载到内存中,我想使用缓冲区释放其中的一些字节。
我可以使用什么为缓冲区提供读数?
简便的方法是使用Commons IO库
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);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句