Java: download a png image and save as file

I'm giving you a simple java code that will download a png image from remote location, lets say from google. And save the image into your local pc. I'm using URLConnection and Java standard I/O libraries to do this task.

When I didn't knew the proper way, I was using PrintWriter and reading the data line by line, and which actually messed the thing. But now its working for me.

Here is the code,


// lets say saving the png file from google.
URL url = new URL("http://www.google.com/intl/en_com/images/logo_plain.png");
URLConnection urlConnection = url.openConnection();

// creating the input stream from google image
BufferedInputStream in = new BufferedInputStream(urlConnection.getInputStream());
// my local file writer, output stream
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream( "image.png" ));

// until the end of data, keep saving into file.
int i;
while ((i = in.read()) != -1) {
out.write(i);
}
out.flush();

// closing all the shits
out.close();
in.close();


Using this simple code, you should be able to download any kind of binary file(pdf, gif, jpg, etc) directly from website to your local pc. you'll just need to change the input URL, and output file name. That's all.

Comments

Anonymous said…
It's really nice code.
Solves my problem.

Thanks,
Venkat
Anonymous said…
very good. iI get it
Unknown said…
Good one!! Have a look at this http://www.compiletimeerror.com/2013/08/java-downloadextract-all-images-from.html to download all images from website.. May help..
Unknown said…
Good one!! Have a look at this http://www.compiletimeerror.com/2013/08/java-downloadextract-all-images-from.html to download all images from website.. May help..
koshka said…
Thank you very much!

I have to add:
urlConnection.addRequestProperty("User-Agent", "Mozilla/4.76");
for the code to work in my program.
But the rest work pretty well