1,创建打开网络的流
URL page = new URL(address)
HttpURLConnection conn = (HttpURLConnection)page.connect();
InputStreamReader in = newInputStreamReader((InputStream)conn.getContent());
BufferedReader buff = new BufferedReader(in)
String line ;
do{
line = buff.readLine();
text.append(line);
text.append("\n");
}while(line!=null);
try{
WebReader wb = new WebReader();
wb.getData(address);
}catch(MalFormeURLException mue){
sysout("URL is wrong");
}
读取网上的文本信息:
a)创建一个表示资源网址的URL对象
b)创建一个HttpURLConnection对象,能够加载URL并连接到相应的站点
c)使用HttpURLConnection对象的getContent()方法创建一个InputStreamReader,用来读取来自URL的数据流
d)使用输出流来创建一个BufferedReader对象,后者能够从输入流中读取字符
注意:
1;使用完整的网络地址
http:\\www.baidu.com
2;使用URL的构造函数需进行异常处理
class WebReader;
public void getData(String address);
3,Example:
package Internet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class WebReader extends JFrame{
JTextArea box = new JTextArea("读取数据");
public WebReader(){
super("得到文件程序");
setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
setSize(500, 300);
JScrollPane pane = new JScrollPane(box);
add(pane);
setVisible(true);
}
void getData(String address) throws MalformedURLException{
setTitle(address);
URL page = new URL(address);
StringBuilder text = new StringBuilder();
try{
HttpURLConnection conn = (HttpURLConnection) page.openConnection();
conn.connect();
String key;;
String header;
int i = 0;
do{
key = conn.getHeaderFieldKey(i);
header = conn.getHeaderField(i);
if(header != null){
text.append(key);
text.append(header);
text.append("\n");
}
i++;
}while(header != null);
text.append("\n");
InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
BufferedReader buff = new BufferedReader(in);
box.setText("get data......");
String line;
do{
line = buff.readLine();
text.append(line);
text.append("\n");
}while(line != null);
box.setText(text.toString());
}catch(IOException ioe){
System.out.println("错误"+ioe.getMessage());
}
}
public static void main(String[] args) {
try{
WebReader app = new WebReader();
app.getData("http://www.baidu.com");
}catch(MalformedURLException mue){
System.out.println("错误的链接");
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class WebReader extends JFrame{
}