java编程经常用到java.net包中的一些类,java.net.URL类是对网络资源地址的表示。注意:URL Uniform Resource Location(统一资源地址)的格式为:
协议名:主机名/目录及文件名
如:http://www.sina.com
下面例子是读取网络上文件的内容。
读取网络文件内容的步骤为:
1.创建一个RUL类型的对象。
URL url="www.sina.com";(协议一定要写,格式不能错)
2.利用URL类的openStream()方法,获得对应的InputStream类的对象。
InputStream filecon=url.openStream();
3.通过InputStream来读取内容。
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
public class Url {
public void urlCon(String path) {
URL url = null;
try {
url = new URL(path);
}
catch(MalformedURLException e) {
System.out.println("你输入的URL地址不正确!");
e.printStackTrace();
}
try {
InputStream urlCon = url.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(urlCon));
String line = null;
while((line=br.readLine())!=null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String path = "http://www.sina.com";
Url url = new Url();
url.urlCon(path);
}
}