# 網路爬蟲輸出 ###### tags: 'Ming' {%hackmd BJrTq20hE %} package ch02; import java.io.*; //java 專門寫給網路應用的類別 import java.net.*; public class GetNatalieFromInternet { public static void main(String[] args) { File dir = new File("D:\\Pictures"); //判斷該檔案路徑下,資料夾是否存在,若不存在則建立資料夾 if (!dir.exists()) { dir.mkdir(); } for (int i = 1; i <= 42; i++) { String url = "http://www.space-fox.com/wallpapers/celebs/natalie-portman" + "/natalie_portman_" + i + ".jpg"; // 取變數"url"的最後一個"/"的索引值並+1的後續字串,作為檔案的輸出名稱 String filename = url.substring(url.lastIndexOf("/") + 1); // file物件 代表輸出的目的地(路徑,檔案名稱) File file = new File(dir, filename); try { //在參數url中,輸入符合網址格式的字串 URL myURL = new URL(url); //將URL父類別轉型為HttpURLConnection,並透過方法建立網路與程式間的通道 HttpURLConnection conn = (HttpURLConnection) myURL.openConnection(); InputStream is = conn.getInputStream(); //確立通道後執行輸出動作 FileOutputStream fos = new FileOutputStream(file); System.out.println("Wallpaper: " + filename + " kick-off!"); int length = 0; //自訂 4KB 緩衝區 但開得太大會占用很多執行環境的記憶體資源 byte[] b = new byte[4096]; while ((length = is.read(b)) != -1) { // b: 代表要輸出的byte陣列 (資料都放在裡面了) // 0: 代表從這個陣列的第一個元素開始輸出 (索引值) // length: 代表要輸出的資料量(此處為 4096 byte) fos.write(b, 0, length); //flush目的在強制資料從緩衝區送出 fos.flush(); } fos.close(); is.close(); System.out.println(filename + " Done!"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up