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

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.

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