多种方式实现java写文件
本文介绍java如何写输入流至文件,首先介绍纯java实现,然后是guava Files实现,最后介绍Apache Commons IO 库,当然还有其他,如之前文章中提到的Spring StreamUtils。
java实现写文件
开始java的实现方式:
@Test
public void whenConvertingToFile_thenCorrect()
throws IOException {
InputStream initialStream = new FileInputStream(
new File("src/main/resources/sample.txt"));
byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
File targetFile = new File("src/main/resources/targetFile.tmp");
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
}
上面示例需要指出,输入流是已知的磁盘文件或内存流,因此无需检查大小,只要内存允许,简单读取并一次性写入即可。
如果输入流与持续的数据流关联,比如当前活动连接的http响应,那么一次性读取整个流是不可取的,这时我们需要确保持续读取,直到流的结尾。
@Test
public void whenConvertingInProgressToFile_thenCorrect()
throws IOException {
InputStream initialStream = new FileInputStream(
new File("src/main/resources/sample.txt"));
File targetFile = new File("src/main/resources/targetFile.tmp");
OutputStream outStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[8 * 1024];
int bytesRead;
while ((bytesRead = initialStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
IOUtils.closeQuietly(initialStream);
IOUtils.closeQuietly(outStream);
}
IOUtils是Commons IO 提供的工具类,用于关闭流。Guava中也有Closer类实现。
java8实现也很简洁:
@Test
public void whenConvertingAnInProgressInputStreamToFile_thenCorrect2()
throws IOException {
InputStream initialStream = new FileInputStream(
new File("src/main/resources/sample.txt"));
File targetFile = new File("src/main/resources/targetFile.tmp");
java.nio.file.Files.copy(
initialStream,
targetFile.toPath(),
StandardCopyOption.REPLACE_EXISTING);
IOUtils.closeQuietly(initialStream);
}
guava实现写文件
guava实现很简单,并且无需关闭。
@Test
public void whenConvertingInputStreamToFile_thenCorrect3()
throws IOException {
InputStream initialStream = new FileInputStream(
new File("src/main/resources/sample.txt"));
byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
File targetFile = new File("src/main/resources/targetFile.tmp");
Files.write(buffer, targetFile);
}
Commons IO实现
commons io 实现代码更少。
@Test
public void whenConvertingInputStreamToFile_thenCorrect4()
throws IOException {
InputStream initialStream = FileUtils.openInputStream
(new File("src/main/resources/sample.txt"));
File targetFile = new File("src/main/resources/targetFile.tmp");
FileUtils.copyInputStreamToFile(initialStream, targetFile);
}
总结
本文介绍了三种java写输入流至文件的方式,形式不重要,重要的是理解其中原理,避免读取效率低且代码冗长。
本文参考链接:https://blog.csdn.net/neweastsun/article/details/79599189