Write an InputStream to a File in Java

May 16, 2020 No comments Java IO Conversions InputStream File Write

1. Introduction

In this tutorial, we are going to learn how to write InputStream to a File in Java. We will use plain Java and libraries with utility classes to process IO operations like Guava and Apache Common IO.

For more Java I/O related articles, check the following links:

2. InputStream to a File using FileOutputStream

Let's start with a plain Java solution. Java provides FileOutputStream class that can be used to write an InputStream to a File:

package com.frontbackend.java.io.conversions;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamToFileUsingFileOutputStream {

    public static void main(String[] args) throws IOException {
        byte[] bytes = { 102, 114, 111, 110, 116, 98, 97, 99, 107, 101, 110, 100 }; // frontbackend
        InputStream inputStream = new ByteArrayInputStream(bytes);

        File file = new File("/tmp/output.txt");
        try (FileOutputStream outputStream = new FileOutputStream(file)) {
            int read;
            byte[] bytes = new byte[1024];

            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
        }
    }
}

In this example, first, we created ByteArrayInputStream filled with sample bytes. Then, in a loop, we read bytes from that InputStream and write them into the FileOutputStream. Bytes are saved in the /tmp/output.txt file using FileOutputStream.write method. In this snippet, we used try-with-resources expression to automatically close OutputStream after IO operations.

3. Write InputStream to File using Files from Java NIO

Java new IO API comes with many utility classes and methods which do a lot of work under the hood. In the following example, we used Files.copy method which is specially designed for processing file streams:

package com.frontbackend.java.io.conversions;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class InputStreamToFileUsingFiles {

    public static void main(String[] args) throws IOException {
        byte[] bytes = { 102, 114, 111, 110, 116, 98, 97, 99, 107, 101, 110, 100 }; // frontbackend
        InputStream inputStream = new ByteArrayInputStream(bytes);

        File file = new File("/tmp/output.txt");
        Files.copy(inputStream, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
}

Files.copy method copies all bytes from an input stream to a file. We just need to fill three arguments of that utility method:

  • the first argument is the input stream to read from,
  • the second parameter is the path to the file,
  • the third parameter contains options specifying how the copy should be done.

In our example, the third argument is set to StandardCopyOption.REPLACE_EXISTING - if the target file exists it will be replaced with the new content.

4. InputStream to File using Guava library

Another way to write InputStream to a File in Java is to use an external library like Guava. The Guava comes with many utility classes dedicated to IO operations. In the following example, we used ByteStreams.copy(inputStream, outputStream) method that simply copy InputStream to the OutputStream (in our case FileOutputStream is our output stream):

package com.frontbackend.java.io.conversions;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.google.common.io.ByteStreams;

public class InputStreamToFileUsingGuava {

    public static void main(String[] args) throws IOException {
        byte[] bytes = { 102, 114, 111, 110, 116, 98, 97, 99, 107, 101, 110, 100 }; // frontbackend
        InputStream inputStream = new ByteArrayInputStream(bytes);

        File file = new File("/tmp/output.txt");
        try (FileOutputStream outputStream = new FileOutputStream(file)) {
            ByteStreams.copy(inputStream, outputStream);
        }
    }
}

Note that ByteStreams.copy operation did not close the streams so we have to do it explicitly.

To start using Guava you have to include a special dependency on your project or download a JAR file. The latest version of Guava library is available under the following links:

5. Convert InputStream to File using Apache Commons IO library

Apache Commons IO is another library we can use to write InputStream to a File in Java. That tool provides the dedicated method that writes an InputStream to the File directly - FileUtils.copyInputStreamToFile(inputStream, file).

This allows us to create a single-line solution:

package com.frontbackend.java.io.conversions;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;

public class InputStreamToFileUsingFileUtils {

    public static void main(String[] args) throws IOException {
        byte[] bytes = { 102, 114, 111, 110, 116, 98, 97, 99, 107, 101, 110, 100 }; // frontbackend
        InputStream inputStream = new ByteArrayInputStream(bytes);

        File file = new File("/tmp/output.txt");

        FileUtils.copyInputStreamToFile(inputStream, file);
    }
}

The latest version of the Apache Commons IO library could be found under the following link: Maven Apache Commons IO 2.6

6. Conclusion

In this article, we presented several ways to write an InputStream to a File using libraries and plain Java. It is really up to you what solution you will choose.

Example snippets used in this tutorial are available under GitHub repository.

{{ message }}

{{ 'Comments are closed.' | trans }}