Java – Write an InputStream to a File – Java –将一个InputStream写入文件

最后修改: 2014年 6月 21日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’ll illustrate how to write an InputStream to a File. First we’ll use plain Java, then Guava, and finally the Apache Commons IO library.

在这个快速教程中,我们将说明如何将一个InputStream写入文件。首先我们将使用普通的Java,然后是Guava,最后是Apache Commons IO库。

This article is part of the Java – Back to Basic” tutorial here on Baeldung.

本文是Ba href=”/java-tutorial” title=”关于IO和集合的Java指南”>”Java – Back to Basic” 教程的一部分。

2. Convert Using Plain Java

2.使用普通的Java进行转换

Let’s start with the Java solution:

让我们从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);
}

Note that in this example, the input stream has known and pre-determined data, such as a file on disk or an in-memory stream. As a result, we don’t need to do any bounds checking and we can, if memory allows, simply read it and write it in one go.

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

If the input stream is linked to an ongoing stream of data, like an HTTP response coming from an ongoing connection, then reading the entire stream once isn’t an option. In that case, we need to make sure we keep reading until we reach the end of the stream:

如果输入流与正在进行的数据流相连,比如来自持续连接的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);
}

Finally, here’s another simple way we can use Java 8 to do the same operation:

最后,这里有另一种简单的方法,我们可以使用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. Convert Using Guava

3.使用Guava进行转换

Next, let’s take a look at a simpler Guava based solution:

接下来,让我们看看一个更简单的基于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. Convert Using Commons IO

4.使用Commons IO进行转换

Finally, here’s an even quicker solution with Apache 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);
}

And there we have it, 3 quick ways of writing the InputStream to a File.

就这样,我们有了3种快速写入InputStream到文件的方法。

The implementation of all these examples can be found in our GitHub project.

所有这些例子的实现都可以在我们的GitHub项目中找到。