How to Convert an InputStream to a File in Java


Let’s see how we many convert an InputStream to a File in Java.

1. InputStream::transferTo (Java 9)

In Java 9, we can copy bytes from an input stream to an output stream using InputStream::transferTo.

static void copyStreamToFile(InputStream in, File file) {
  try (OutputStream out = new FileOutputStream(file)) {
    in.transferTo(out);
  } catch (IOException e) {
    e.printStackTrace();
  }
}

2. Files::copy (Java 7)

In Java 7, we can use Files::copy to copy bytes from an input stream to a file.

static void copyInputStreamToFile(InputStream in, File file) {
  Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

3. IOUtils::copy (Apache Commons IO)

With commons-io we have access to IOUtils::copy, which will allow us to copy bytes from one stream to another (in this case, a FileOutputStream).

static void copyStreamToFile(InputStream in, File file) {
  try (OutputStream out = new FileOutputStream(file)) {
    IOUtils.copy(in, out);
  } catch (FileNotFoundException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

4. FileUtils::copyInputStreamToFile (Apache Commons IO)

With commons-io, we also have access to FileUtils::copyInputStreamToFile to copy a source stream into a file destination.

static void copyStreamToFile(InputStream in, File file) {
  FileUtils.copyInputStreamToFile(in, file);
}

5. Plain Java (no external libraries)

If we decide to use plain Java, we can manually read the bytes from the input stream to some output stream.

static void copyStreamToFile(InputStream in, File file) {
  OutputStream out = new FileOutputStream(file);
  byte[] buffer = new byte[1024];
  int read;
  while ((read = in.read(buffer)) != -1) {
    out.write(buffer, 0, read);
  } 
  out.close();
}