Java – How to convert InputStream to File

In this post we will demonstrate how to convert the contents of an input stream to a File using Java. Below is two examples one using core java the other is using the Apache Commons IO library.

Convert InputStream to File using Apache Commons IO:

For this example you will need to add the following dependency:

Below is an example of how to convert an InputStream with random content to a File. The IOUtils class has a static method toInputStream() which will convert your content to an InputStream. FilesUtils has a static method copyInputStreamToFile() which will copy the content in the input stream and write it to a file. Both IOUtils and FileUtils are classes from the apache commons library.

Running the above code will create a file called ‘test1.txt’ with the content specified in the InputStream.

Convert InputStream to File:

If however, you don’t want to include an external library you can achieve the same result with the standard JDK libraries. The example below is a bit more involved.

  • It first defines a String contents which is then converted to an InputStream using the ByteArrayInputStream class
  • It converts the InputStream to a BufferedReader using the InputStreamReader so that we can process each line
  • Using the BufferedReader we go through each line and write it to file.

Running the above code produces the same result as the first example i.e. a new file is created ‘test2.txt’ with the contents of the InputStream.

In conclusion, I hope you found this post of some use and that it has helped you solve your coding problem.

Similar posts:

  1. How to write to a file in Java
  2. List files in a directory
  3. How to create a file in Java
  4. Java 8 Stream map example

References:

  1. Apache Commons IO Documentation
  2. Java Basic IO tutorials

Leave a Reply