How to convert InputStream to File in Java

Below are some Java examples to convert InputStream to File

  1. Copy InputStream to FileOutputStream manually
  2. Apache Commons IO – FileUtils.copyInputStreamToFile
  3. Java 1.7 NIO Files.copy

1. FileOutputStream

1.1 We have to copy the data from InputStream into OutputStream manually.

InputStreamToFile.java

package com.mkyong;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

public class InputStreamToFile {

    private static final String FILE_TO = "d:\\download\\google.txt";

    public static void main(String[] args) throws IOException {

        URI u = URI.create("https://www.google.com/");
        try (InputStream inputStream = u.toURL().openStream()) {
            File file = new File(FILE_TO);
            copyInputStreamToFile(inputStream, file);
        }
    }

    // InputStream -> File
    private static void copyInputStreamToFile(InputStream inputStream, File file) 
		throws IOException {

        try (FileOutputStream outputStream = new FileOutputStream(file)) {

            int read;
            byte[] bytes = new byte[1024];

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

			// commons-io
            //IOUtils.copy(inputStream, outputStream);

        }

    }

}

2. Apache Commons IO

2.1 FileUtils.copyInputStreamToFile is available in the Apache Commons IO

pom.xml

	<dependency>
		<groupId>commons-io</groupId>
		<artifactId>commons-io</artifactId>
		<version>2.6</version>
	</dependency>
InputStreamToFile2.java

package com.mkyong;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

public class InputStreamToFile2 {

    private static final String FILE_TO = "d:\\download\\google.txt";

    public static void main(String[] args) throws IOException {

        URI u = URI.create("https://www.google.com/");
        try (InputStream inputStream = u.toURL().openStream()) {

            File file = new File(FILE_TO);

			// commons-io
            FileUtils.copyInputStreamToFile(inputStream, file);
        }

    }

}

3. Java 1.7 NIO

3.1 If just want to save inputStream into a file somewhere, try the Java 1.7 NIO Files.copy

InputStreamToFile3.java

package com.mkyong;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;

public class InputStreamToFile3 {

    private static final String FILE_TO = "d:\\download\\google.txt";

    public static void main(String[] args) throws IOException {

        URI u = URI.create("https://www.google.com/");
        try (InputStream inputStream = u.toURL().openStream()) {

			//Java 1.7
            Files.copy(inputStream, Paths.get(FILE_TO));

        }

    }

}

4. Old Days

4.1 In the old days, before Java 1.7, we have to close all resources manually.

InputStreamToFile4.java

package com.mkyong;

import java.io.*;

public class InputStreamToFile4 {

    public static void main(String[] args) {

        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            // read this file into InputStream
            inputStream = new FileInputStream("/Users/mkyong/holder.js");

            // write the inputStream to a FileOutputStream
            outputStream = new FileOutputStream(new File("/Users/mkyong/holder-new.js"));

            int read = 0;
            byte[] bytes = new byte[1024];

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

            System.out.println("Done!");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

}

5. Convert File to InputStream

It is much easy :


	File file = new File("d:\\download\\google.txt");
    InputStream inputStream = new FileInputStream(file);
Note
You may interest at this InputStream to String

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
13 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
13 Comment authors
krishChaitanyaMartinmerveBhart Recent comment authors
newest oldest most voted
jeffdav
Guest
jeffdav

There is a bug in this code. If the input stream contains less that 1024 bytes the resulting file will always be 1024 bytes. This may not matter, but if, for example, you want to take the MD5 hash of the file it will be wrong, etc.

Instead do something like:

int bytesWritten = 0;
int byteCount = 0;
byte[] bytes = new byte[1024];
while ((byteCount = input.read(bytes)) != -1) {
output.write(bytes, bytesWritten, byteCount);
bytesWritten += byteCount;
}

Angel
Guest
Angel

Omg, this is amazing;
You helped me like 4 times with spring,springmvc and maven, and now this;
I admire you;
thank you really

shinigami
Guest
shinigami

YOU RE GREAT!!!!!

ITEDVO
Guest
ITEDVO

Thats great, thank you very much!

I need that because I use ini4j to read / write ini-files.
The constructor needs a File-object but from URL i get an InputStream Object ^^

Thank you very much, with your solution it works fine!

Ravi.S
Guest
Ravi.S

Thats great, thank you very much!

Mhappyboy Forms Coupons
Guest
Mhappyboy Forms Coupons

Hello there, just became alert to your blog through Google, and
found that it’s really informative. I am gonna watch out for brussels. I will appreciate if you continue this in future. Numerous people will be benefited from your writing. Cheers!

Gerardo
Guest
Gerardo

Dude, your code save my life lol, Greetings.

Bhart
Guest
Bhart

Thanks! But this is not working for XLSX Spreadsheet. Can you please suggest how to save the spreadsheet to file system after importing?

merve
Guest
merve

thnks but where is output “File” variable then at 2.

Martin
Guest
Martin

Thanks buddy! Helped a lot!

Chaitanya
Guest
Chaitanya

Why the byte[] bytes length is 1024?

krish
Guest
krish

How to Unzip a file with passsowrd in java?

krish
Guest
krish

Uncompress a zip file using password?