程式碼是參考站內大大的,因為自己的程式碼寫太多,所以貼上參考的程式碼
我讀取網頁內容時,有時候可以讀取,但有時候會發生錯誤,請問是哪裡出了問題?
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class SimpleURL2 {
public static void main(String[] args) throws IOException {
URL url = new URL("http://ithelp.ithome.com.tw/ironman7/app/index");
URLConnection conn = url.openConnection();
conn.connect();
String type = conn.getContentType();
System.out.println("Context: "+type);
FileWriter fw = new FileWriter("/Users/yfsun/Documents/Hi_Day10.txt");
InputStreamReader in = new InputStreamReader(conn.getInputStream(),"UTF-8");
int data = in.read();
while (data != -1){
System.out.print((char)data);
data = in.read();
fw.write(data);
fw.flush();
}
in.close();
fw.close();
}
}
![http://ithelp.ithome.com.tw/upload/images/20161027/201030894jb9c8XhMZ.png](http://ithelp.ithome.com.tw/upload/images/20161027/201030894jb9c8XhMZ.png)