Contents

将InputStream写入文件

1. 概述

在本快速教程中,我们将说明如何将**InputStream写入文件。**首先我们将使用纯 Java,然后是 Guava,最后是 Apache Commons IO 库。

2. 使用纯 Java 进行转换

让我们从Java 解决方案开始:

@Test
public void whenConvertingToFile_thenCorrect() throws IOException {
    Path path = Paths.get("src/test/resources/sample.txt");
    byte[] buffer = java.nio.file.Files.readAllBytes(path);
    File targetFile = new File("src/test/resources/targetFile.tmp");
    OutputStream outStream = new FileOutputStream(targetFile);
    outStream.write(buffer);
    IOUtils.closeQuietly(outStream);
}

请注意,在此示例中,输入流具有已知和预先确定的数据,例如磁盘上的文件或内存中的流。因此,我们不需要做任何边界检查,如果内存允许,我们可以简单地一次性读取和写入。

如果输入流链接到正在进行的数据流,例如来自正在进行的连接的 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);
}

最后,这是我们可以使用 Java 8 执行相同操作的另一种简单方法:

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

3. 使用 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);
}

4. 使用 Commons IO 转换

最后,这里有一个更快的 Apache 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);
}

我们已经有了 3 种将InputStream写入文件的快速方法。