1. 程式人生 > >java根據圖片的url地址下載圖片到本地

java根據圖片的url地址下載圖片到本地

package com.daojia.haobo.aicircle.util;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

    public class DownloadPicFromUrl {
        public static void main(String[] args) {
            String url = "http://XXXXXX33ayDdEs%3D";
            String path
="c:/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); } BASE64Encoder encoder = new BASE64Encoder(); String encode = encoder.encode(buffer);//返回Base64編碼過的位元組陣列字串 System.out.println(encode); fileOutputStream.write(output.toByteArray()); dataInputStream.close(); fileOutputStream.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }