java - 无法使用 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();
}
}
解决方案
我建议为您的 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());
}
}
推荐阅读
- docker - 为什么 Docker CMD 在 GKE 中作为 chronos 运行?
- r - 将表作为函数参数和值传递
- api - 有没有办法在 Strapi 中动态存储 API 请求响应?
- mysql - MySQL将两个表合并在一起并使用第二个表中最近插入的行进行排序
- python - 无法使用 Selenium(Python)单击按钮
- docker - Docker & docker-compose:当挂载为卷时,使主机和容器都可以访问目录
- javascript - 自动完成错误:未捕获的类型错误:无法读取未定义的属性“构造函数”
- zfs - 使用数千个数据集创建缓慢的 zfs
- php - 如何对它们之间相关的数据分层数组进行排序
- python - 如何在pygame中添加闪烁的光标?