I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

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 Baeldung.

Further reading:

Java – InputStream to Reader

How to convert an InputStream to a Reader using Java, Guava and the Apache Commons IO library.

Read more

Java – Convert File to InputStream

How to open an InputStream from a Java File - using plain Java, Guava and the Apache Commons IO library.

Read more

Java InputStream to Byte Array

How to convert an InputStream to a byte[] using plain Java, Guava or Commons IO.

Read more

2. Convert using plain Java

Let’s start with the Java solution:

@Test
public void whenConvertingToFile_thenCorrect() 
  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");
    OutputStream outStream = new FileOutputStream(targetFile);
    outStream.write(buffer);
}

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.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS

Sort by:   newest | oldest | most voted
Brian Pontarelli
Guest

Your Java example is lacking a bounds check. The read method might not read the full byte array.

Eugen Paraschiv
Guest
Hey Brian – thanks for pointing that out. It was something I considered adding here, but there’s a distinction to be made between an InputStream that may have data coming into it (such as perhaps an ongoing response for a server) and an InputStream that has a per-determined and fixed data load – such as a file on disk. For this case (which is the case in the example) – the buffer will be sized according to the file size and so there will be no need for bounds checking – the entire file will be copied over. That being… Read more »
Brian Pontarelli
Guest

Right and your example will only work if everything just happens to line up: The file system, kernel buffers, the disk cache, the bus, the paging, Java buffers, etc. Everything needs to have enough space, otherwise this will fail. This is usually the case for small files, but not always. I believe it also depends on the IO load on the computer as well.

Eugen Paraschiv
Guest

Yeah, you’re definitely right in the fact that it doesn’t deal with corner cases, error handling, etc – so it’s definitely not something I’d recommend to go into production with. On the other hand this is an intro level article that basically shows you how to perform the main operation. Dealing with both usecases – the one where the InputStream has all the data, and the other, where it doesn’t – makes sense, but I wouldn’t go to far beyond that an such an intro piece. Hope that makes sense.

karol
Guest

Hi.

This article is the first result of the query “java inputstream to file” on Google. I can assure you that it is now in production somewhere.

Eugen Paraschiv
Guest

That may very well be – but that’s the case with most StackOverflow answers for example, and any intro-level tutorial out there.
If someone’s doing copy-paste coding, and not making an effort to understand the information they’re readying and make an informed decision as to how they’re using that information – then yes, things are not going to work out, in general, and in particular when they’re converting from an input stream to a file.

sathishkumarthiyagarajan
Guest
sathishkumarthiyagarajan

We can use Files utility in Core Java

File newFile = new File(“<>”);
newFile.mkdirs();
Files.copy(<>, newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

Eugen Paraschiv
Guest

That’s a good point – I’m adding a new example into the article now. Cheers,
Eugen.