1. 程式人生 > >IO流從url路徑中獲取內容儲存到本地的檔案中

IO流從url路徑中獲取內容儲存到本地的檔案中

 要點:

1.建立輸出的檔案目錄與檔案

2.輸入輸出流的同時運用以及char陣列的快取

3.關閉方法

package com;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;

public class save {
	public static void main(String [] args){
		//使用File類建立一個要操作的檔案路徑
		String savePath = "E:/aa/bbb/a.txt";
		File file = new File(savePath);
		//如果檔案目錄不出在則建立目錄 *getParentFile()*
		if(!file.getParentFile().exists()){//判斷檔案目錄是否存在
			file.getParentFile().mkdirs();//建立目錄
		}
		
		//使用url 讀取網頁內容
		String path = "https://www.baidu.com/";
		//可以建立url例項
		URL url;
		try {
			url = new URL(path);
		//位元組輸入流
		InputStream is = url.openStream();
		//位元組流轉字元流
		InputStreamReader isr = new InputStreamReader(is,"UTF-8");
		//再轉緩衝流  提高讀取效率
		BufferedReader br = new BufferedReader(isr);
		
		//檔案輸出流
		OutputStream output = new FileOutputStream(file);
		//字元緩衝流輸出                                                                       轉化流
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(output));
		
		//使用char 陣列傳輸    -----位元組流byte陣列
		char [] chs = new char[1024];
		//標記
		int len = 0;

		while((len = br.read(chs)) != -1){// read() 方法,讀取輸入流的下一個位元組,返回一個0-255之間的int型別整數。如果到達流的末端,返回-1
			bw.write(chs, 0, len);//寫入檔案
			bw.flush();//清除快取
		}
		
		close(bw,br);
		
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 *關閉方法 
	 */
	private static void close (AutoCloseable ...ac ){
		for (AutoCloseable autoCloseable : ac) {
			if (autoCloseable != null) {
				try {
					autoCloseable.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}