Java examples for 2D Graphics:Image File
save URL Image To File
//package com.java2s; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.zip.GZIPInputStream; public class Main { public static void saveURLImageToFile(String urlPath, String fileSavePath) throws IOException { FileOutputStream fos = null; BufferedInputStream bis = null; HttpURLConnection httpUrl = null; URL url = null;/*w w w . ja v a2 s. c o m*/ int BUFFER_SIZE = 1024; byte[] buf = new byte[BUFFER_SIZE]; int size = 0; try { url = new URL(urlPath); httpUrl = (HttpURLConnection) url.openConnection(); httpUrl.connect(); File file = new File(fileSavePath); if (!file.getParentFile().exists()) file.getParentFile().mkdirs(); String zipFormatter = httpUrl .getHeaderField("Content-Encoding"); InputStream is = httpUrl.getInputStream(); if (zipFormatter != null && zipFormatter.equals("gzip")) is = new GZIPInputStream(is); bis = new BufferedInputStream(is); fos = new FileOutputStream(fileSavePath); while ((size = bis.read(buf)) != -1) { fos.write(buf, 0, size); } } catch (IOException e) { } catch (ClassCastException e) { } finally { if (fos != null) { fos.flush(); fos.close(); } if (bis != null) { bis.close(); } if (httpUrl != null) { httpUrl.disconnect(); } } } }