0

任何人都可以帮助我使用 Java URL 阅读器吗?

我在 Java 中创建了一个 URL 阅读器,它读取链接并将其发送到特定文件。如何从两个 URL 读取代码并将其保存到特定文件中?

这是我的代码:

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

public class URLReader {

public static void main(String[] args) throws Exception {

    URL oracle = new URL("http://www.oracle.com/");
    URLConnection yc = oracle.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(
    yc.getInputStream()));

    String inputLine;
    BufferedWriter psout = new BufferedWriter(new FileWriter("D:\\final.txt"));
    while ((inputLine = in.readLine()) != null) {
    psout.write(inputLine);
    System.out.println(inputLine);
    }
    in.close();
    psout.close();
   }
}
4

2 回答 2

0

如果您打算写入单个文件,则可以将其提取到一个方法中并使用appendin 参数FileWriter

private static void saveURL(String urlString) throws MalformedURLException, IOException {
   URL url = new URL(urlString);
   URLConnection yc = url.openConnection();
   BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));

   String inputLine;
   BufferedWriter psout = new BufferedWriter(new FileWriter("final.txt", true));

   // write file...

}
于 2012-10-29T19:19:20.820 回答
0

如果我理解您的问题,您想将两个不同 URL 的内容写入同一个文件。您可以拥有一个 URL 对象列表,然后从列表中读取/写入迭代。

List<URL> al = new ArrayList<>();
      URL oracle = new URL("http://www.oracle.com/");
      URL google =new  URL("http://www.google.com");
      al.add(oracle);
      al.add(google);
      BufferedReader in=null;
      BufferedWriter psout=null;
      for(URL url: al){
      URLConnection yc = url.openConnection();
      in = new BufferedReader(new InputStreamReader(
      yc.getInputStream()));
      String inputLine;
     psout = new BufferedWriter(new FileWriter("final.txt"));
      while ((inputLine = in.readLine()) != null) {
      psout.write(inputLine);
      System.out.println(inputLine);
      }

      }      in.close();
      psout.close();
于 2012-10-29T19:25:42.017 回答