In this post we’ll Download image from specified URL in java
Let’s download image of this tiger.
URL of this image = “https://lh4.googleusercontent.com/cjh5t_mnSYuW_RnVI922M9kjxW8leJGp8nCwWdBjOQxz_RzNkuvVIHaxzDrZ-neDiFt71jyRKAQ4_2DTiv6R_vlZX0uUBGxLWmDR6Wa2gqqPJhgF7UzfqwYQJLTnDH0fKPt7wUc”
Program to Download image from specified URL in java >
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class DownloadImageFromSpecifiedURL {
public static void main(String[] args) throws IOException {
//Specify URL from which file will be downloaded.
URL url = new URL(
"https://lh4.googleusercontent.com/"
+ "cjh5t_mnSYuW_RnVI922M9kjxW8leJGp8nCwWdBjOQxz_RzNkuvVIHaxzDrZ-neDiFt71jyRKAQ4_"
+ "2DTiv6R_vlZX0uUBGxLWmDR6Wa2gqqPJhgF7UzfqwYQJLTnDH0fKPt7wUc");
String downloadFileLocation = "C:/downloadedImage.jpg";
//Read image from specified URL using InputStream
InputStream is = url.openStream();
//Write image to file using FileOutputStream
OutputStream fos = new FileOutputStream(downloadFileLocation);
int ch;
while ((ch = is.read()) != -1) { //read till end of file
fos.write(ch);
}
System.out.println("Image from specified URL has been downloaded at "
+downloadFileLocation);
is.close();
fos.close();
}
}
/*OUTPUT
Image from specified URL has been downloaded at C:/downloadedImage.jpg
*/
|
RELATED LINKS>
Find current working directory or current path in java
Read text from file using BufferedInputStream (and FileInputStream) in java file IO
Difference between loading file with FileInputStream and getResourceAsStream() in java
Difference between getPath(), getAbsolute() and getCanonical() file path methods in java | Relative and Absolute path
Labels:
Core Java