JAVA中URL类的常用方法

1.URL类中的常用方法:

//创建一个URL对象
    URL url = new URL("http://www.baidu.com");  
    URL url1 = new URL(url, "/index.html?usrname=lqq#test");
//url的常用方法
    System.out.println("URL主机名称:"+url1.getHost());
    System.out.println("URL协议:"+url1.getProtocol());
    System.out.println("URL端口:"+url1.getPort());
    System.out.println("URL文件路径:"+url1.getPath());
    System.out.println("URL查询字符串:"+url1.getQuery());
    System.out.println("URL相对路径:"+url1.getRef());
    System.out.println("URL文件名:"+url1.getFile());   

2.通过URL获取html文件内容:

//创建一个URL实例
URL url = new URL("http://www.baidu.com");
//通过URL对象的openstream方法获取一个InputStream对象
InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);

File bd = new File(".../baidu.html");
PrintWriter pw = new PrintWriter(bd);
//按行读取
String s = br.readLine();
while(s!=null){
    pw.print(s);
    pw.flush();
    s=br.readLine();
}
//关闭相关资源
pw.close();
br.close();
isr.close();
is.close();

你可能感兴趣的:(JAVA)