2012-11-19 68 views
0

下面的代码保存网页内容到一个文件的名称:保存文件与网站

import java.net.*; 
import java.io.*; 



public class url 
{ 
     public static void main(String[] args) 
     { 
      try 
        { 
        URL PageUrl; 
        URLConnection GetConn = null; 
        GetConn = null; 

        PageUrl = new URL("https://www.google.ru/"); 
        GetConn = PageUrl.openConnection(); 

        GetConn.connect(); 

        InputStreamReader ReadIn = new InputStreamReader(GetConn.getInputStream()); 
        BufferedReader BufData = new BufferedReader(ReadIn); 
        String htmlFileName = ("C:\\hello.html"); 
        FileWriter FWriter = new FileWriter(htmlFileName); 
        BufferedWriter BWriter = new BufferedWriter(FWriter); 
        String UrlData = null; 
        while ((UrlData = BufData.readLine()) != null) 
        { 
          BWriter.write(UrlData); 
          BWriter.newLine(); 
        } 
        BWriter.close(); 
       } 
       catch(IOException io) 
       { 
        System.out.println(io); 
       } 
     } 
} 

但我需要的文件具有相同的名称作为网站的页面,例如,它必须以某种方式获取网页的名称并将其指定为文件的名称。

+0

我还是新的,而且还是不明白这一点,你可以编写代码,我敢肯定,这很容易让你 –

回答

2

您可以使用URL.getFile()来获取文件名。即

... 
String htmlFileName = PageURL.getFile(); 
... 

需要注意的是不同的URL可能指向同一个文件:http://example.com/test.html#anch1http://example.com/test.htmlhttp://example.com/test.html?a=b - 所有这三个指同一test.html文件在这里。在这种情况下,您可能想要以某种方式组合getFile(),getRef()getQuery()

值得一提在你的代码的一些问题:

  1. lowerCase代替UpperCase开始的变量名;
  2. 关闭finally区块中的资源。更好的是,如果您使用Java 7,请使用try-with-resources
+0

非常感谢你,可以插入,你有没有在我的代码 –

+0

什么意见我认为文本*“'lowerCase'而不是'UpperCase'”*应该删除代码块(因为这些词不是代码),而是指向[direct](http://en.wikipedia)。 org/wiki/Naming_convention_(编程)#Java)或[indirect](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html),[general](http://www.oracle.com) .com/technetwork/java/javase/documentation/codeconvtoc-136057.html)或[specific](http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367)Java代码公约文件。 – XenoRo