网络图片获取工具类
import com.manage.utils.MD5Util; import org.apache.wicket.common.utils.DateUtils; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class UrlImg { /** * * @param url 网络图片地址 * @param filePath 保存图片的父级文件夹路径 * @return */ public String downloadImgByUrl(String url, String filePath) { FileOutputStream fos=null; BufferedInputStream bis = null; HttpURLConnection httpUrl=null; URL netUrl = null; String fileName=""; try { netUrl = new URL(url); httpUrl = (HttpURLConnection) netUrl.openConnection(); httpUrl.connect(); bis = new BufferedInputStream(httpUrl.getInputStream()); String time = DateUtils.getTimeRandom("yyMMddhhmmss"); fileName = MD5Util.MD5(time) + ".gif";//图片的类型,我默认设定为jpg格式;可以自定义文件类型的,网络图片地址应该会有图片类型的,这里就需要你自己去看一下网络图片地址的规则了 filePath =filePath+"/"+fileName; File outFile = new File(filePath); if (!outFile.exists()) { outFile.createNewFile(); } fos=new FileOutputStream(outFile); byte[] buffer = new byte[3042]; int bytesRead = 0; while ((bytesRead = bis.read(buffer)) != -1) { fos.write(buffer, 0, bytesRead); } fos.close(); bis.close(); } catch (Exception e) { e.getMessage(); System.out.print("请确认网络图片是否正确!"); } return fileName; } public static void main(String [] args){ new UrlImg().downloadImgByUrl("http://img0.pconline.com.cn/pconline/1411/04/5676078_2013123010564417351_thumb.gif","D:\\二维码"); } }