/** * * @param fromUrl 从哪里download? 该图片的原始路径 比如:http://c.hiphotos.baidu.com/image/pic/item/c2cec3fdfc039245c4556c698494a4c27c1e25f7.jpg * @param toUrl download到那里去? D:/test/myImg/ * @param newFileName 新文件名称 my_first.jpg * @return * @throws IOException */ public static String DownloadFile(String fromUrl,String toUrl,String newFileName) throws IOException{ URLConnection con=null; URL theUrl=null; try { theUrl=new URL(fromUrl);//建立地址 con = theUrl.openConnection();//打开连接 con.setConnectTimeout(30000); con.connect();//连接 } catch (MalformedURLException e) { return "给定的URL地址有误,请查看"; } catch (IOException e) { return "无法连接到远程机器,请重试!"; } File filePath = new File(toUrl); if(filePath.exists()==false){ filePath.mkdirs(); } File file=new File(toUrl+newFileName); if(!file.exists()){ file.createNewFile(); } String type = con.getContentType(); if (type != null) { byte[] buffer = new byte[4 * 1024]; int read; try { FileOutputStream os = new FileOutputStream(file); InputStream in = con.getInputStream();//重定向输入 while ((read = in.read(buffer)) > 0) {//读取输出 os.write(buffer, 0, read);//写入本地文件 } os.close(); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return "所要下载的文件不存在!"; }catch (IOException e) { e.printStackTrace(); return "读取远程文件时出错!"; } } else { return "文件未找着:"+fromUrl; } return "拷贝成功"; }
Java实现网络图片下载 / java 图片下载小工具
猜你喜欢
转载自fang-jianqin.iteye.com/blog/2206848
今日推荐
周排行