Java – Write an InputStream to a File

1. Overview

In this quick tutorial, we’re going to illustrate how to write an InputStream to a File – first using plain Java, then Guava, and finally the Apache Commons IO library.

This article is part of the “Java – Back to Basic” tutorial here on VietMX’s Blog.

2. Convert Using Plain Java

Let’s start with the Java solution:

@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. Because of this, we don’t need to do any bounds checking and we can – if memory allows – simply read it and write it in one go.

Java - Write an Input Stream to a File

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

@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 yet another, simple way we can use Java 8 to do the same operation:

@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

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

@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

And finally – an even quicker solution with 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 you have it – 3 quick ways of writing the InputStream to a File.

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

Related posts:

Java Program to Implement Bucket Sort
Java Program to Implement HashSet API
Thao tác với tập tin và thư mục trong Java
Java Program to Perform Polygon Containment Test
Java Program to Implement Gabow Algorithm
Rate Limiting in Spring Cloud Netflix Zuul
Programmatic Transaction Management in Spring
Java Program to Implement Binary Heap
Spring JDBC
Java Program to Implement D-ary-Heap
Form Validation with AngularJS and Spring MVC
Transactions with Spring and JPA
Guide to Java 8’s Collectors
Java Program to Implement the Edmond’s Algorithm for Maximum Cardinality Matching
Debugging Reactive Streams in Java
Enum trong java
Filtering and Transforming Collections in Guava
Lập trình đa luồng với Callable và Future trong Java
Java Program to Solve a Matching Problem for a Given Specific Case
Java Program to Find MST (Minimum Spanning Tree) using Prim’s Algorithm
Kết hợp Java Reflection và Java Annotations
Hướng dẫn Java Design Pattern – Service Locator
Java Program to Implement Interval Tree
Các chương trình minh họa sử dụng Cấu trúc điều khiển trong Java
Java Program to Find the Longest Subsequence Common to All Sequences in a Set of Sequences
Guava Collections Cookbook
Java Program to Implement Sorted Doubly Linked List
Inheritance with Jackson
Spring REST API + OAuth2 + Angular (using the Spring Security OAuth legacy stack)
Java CyclicBarrier vs CountDownLatch
Java Program to Compute the Area of a Triangle Using Determinants
Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers