简体   繁体   English

无法使用 java 将网页内容打印到本地系统中的文件

[英]cannot print webpage contents to a file in my local system using java

I cannot print contents of a webpage to a file in my local system.please help me to solve this problem我无法将网页内容打印到本地系统中的文件中。请帮助我解决此问题

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();
    }
}

I would suggest using a try-with-resources structure for you I/O and take a look a java-naming conventions.我建议为您的 I/O 使用 try-with-resources 结构,并查看 java 命名约定。 If you want to write the output of your http-call to a file you can do the following:如果要将 http 调用的输出写入文件,可以执行以下操作:

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());
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM