java根据图片的url地址下载图片到本地
已知图片的url地址,通过java代码下载到本地,直接上代码
package demo; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; public class DownloadPicFromURL { public static void main(String[] args) { String url = "http://192.168.1.158/estun_cs/banner_img/head_pic.jpg"; String path="d:/test/pic.jpg"; downloadPicture(url,path); } //链接url下载图片 private static void downloadPicture(String urlList,String path) { URL url = null; try { url = new URL(urlList); DataInputStream dataInputStream = new DataInputStream(url.openStream()); FileOutputStream fileOutputStream = new FileOutputStream(new File(path)); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = dataInputStream.read(buffer)) > 0) { output.write(buffer, 0, length); } fileOutputStream.write(output.toByteArray()); dataInputStream.close(); fileOutputStream.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/13898.html