2017年2月19日 星期日

java抓取网络图片放到本地

這篇紀錄了如何使用Java獲取網路上的檔案,程式碼很簡單,直接把程式碼寫出

package readFileFromUrlTest;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ReadFileFromUrlTest {

    public static void main(String[] args) {
        ReadFileFromUrlTest readFileFromUrlTest = new ReadFileFromUrlTest();
        String url = "https://www.vermontteddybear.com/media/wysiwyg/VTB-CMS-Content/featuredcat-KBKF36004-20170119.jpg";
        String filePath = "D:\\xxx.jpg";
        try {
            readFileFromUrlTest.readFileFromUrl(new URL(url), new File(filePath));
        } catch (IOException ex) {
            Logger.getLogger(ReadFileFromUrlTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void readFileFromUrl(URL url, File file) throws IOException {
        BufferedInputStream bufferedInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            bufferedInputStream = new BufferedInputStream(url.openStream());
            fileOutputStream = new FileOutputStream(file);
            int data;
            //從串流讀取資料寫到檔案中
            while ((data = bufferedInputStream.read()) != -1) {
                fileOutputStream.write(data);
            }
        } catch (IOException ex) {
            throw ex;
        } finally {
            //關閉串流
            try {
                if (file != null) {
                    fileOutputStream.close();
                }
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
            } catch (IOException ex) {
                throw ex;
            }
        }
    }

}


參考資料:

  1. java抓取网络图片放到本地


沒有留言 :

張貼留言