使用java.net包下的URL類,可以將一個網頁(鏈接)封裝成一個URL對象。
URL對象有一個openStream()
方法,使用該方法可以獲取該網頁的輸入流,我們可以通過讀取輸入流的方式獲得網頁的內容,並通過輸出流寫入HTML文件中。
方式一:
使用此方法需要指定輸入流和輸出流的字符編碼,否則可能會出現亂碼
步驟:
1. 通過URL對象的openStream()
方法獲得網頁的字節輸入流
2. 將字節輸入流轉換成字符輸入流
3. 爲字符輸入流加緩衝區
4. 定義一個字節輸出流
5. 將字節輸出流轉換成字符輸出流
6. 將讀取到的數據寫入文件
7. 關閉流
public void way_1() throws Exception {
InputStream inputStream;//接收字節輸入流
InputStreamReader inputStreamReader;//將字節輸入流轉換成字符輸入流
BufferedReader bufferedReader;//爲字符輸入流加緩衝
FileOutputStream fileOutputStream;//字節輸出流
OutputStreamWriter outputStreamWriter;//將字節輸出流轉換成字符輸出流
URL wangyi = new URL("http://www.163.com/");
inputStream = wangyi.openStream();
inputStreamReader = new InputStreamReader(inputStream, "gb2312");
bufferedReader = new BufferedReader(inputStreamReader);
String s;
File dest = new File("src/wangyi.html");
fileOutputStream = new FileOutputStream(dest);
outputStreamWriter = new OutputStreamWriter(fileOutputStream, "gb2312");
while ((s = bufferedReader.readLine()) != null) {
outputStreamWriter.write(s);
}
outputStreamWriter.close();
fileOutputStream.close();
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
}
方式二:
使用此方法不需要指定輸入流和輸出流的字符編碼(因爲是通過字節的方式)
步驟:
1. 通過URL對象的openStream()
方法獲得網頁的字節輸入流
2. 爲字節輸入流加緩衝
3. 創建字節輸出流對象
4. 爲字節輸出流加緩衝
5. 讀取數據,並寫入HTML文件
6. 關閉流
public void way_2() throws Exception{
File dest = new File("src/wangyi2.html");
InputStream is;//接收字節輸入流
FileOutputStream fos = new FileOutputStream(dest);//字節輸出流
URL wangyi = new URL("http://www.163.com/");
is = wangyi.openStream();
BufferedInputStream bis = new BufferedInputStream(is);//爲字節輸入流加緩衝
BufferedOutputStream bos = new BufferedOutputStream(fos);//爲字節輸出流加緩衝
int length;
byte[] bytes = new byte[1024*20];
while((length = bis.read(bytes, 0, bytes.length)) != -1){
fos.write(bytes, 0, length);
}
bos.close();
fos.close();
bis.close();
is.close();
}