首页 > 解决方案 > 无法使用 java 将网页内容打印到本地系统中的文件

问题描述

我无法将网页内容打印到本地系统中的文件中。请帮我解决这个问题

import java.net.*;

import java.io.*;

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

        URL oracle = new URL("http://www.google.com/");
        BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));

        OutputStream os = new FileOutputStream("my file location");


        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
    }
}

标签: java

解决方案


我建议为您的 I/O 使用 try-with-resources 结构并查看 java 命名约定。如果要将 http-call 的输出写入文件,可以执行以下操作:

public static void main(String[] args) throws Exception {
  URL googleUrl = new URL("http://www.google.com/");
  try (BufferedReader in = new BufferedReader(new 
    InputStreamReader(googleUrl.openStream()));
    PrintWriter out = new PrintWriter(new FileWriter("path/to/desired/file"))) {
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
      System.out.println(inputLine);
      out.println(inputLine);
    }
  }
  catch (Exception e) {
    System.out.println(e.getMessage());
  }
}

推荐阅读