gpt4 book ai didi

java - 将输出写入文本文件

转载 作者:行者123 更新时间:2023-12-01 17:37:10 24 4
gpt4 key购买 nike

我想将以下输出写入文本文件。我知道这很容易,但我想我在这里忘记了一些基础知识。

我尝试使用“BufferedWriter”,但找不到要传递给编写器的变量输出。有人可以帮忙吗?

import org.jsoup.Jsoup;

import org.jsoup.helper.Validate;

import org.jsoup.nodes.Document;

import org.jsoup.nodes.Element;

import org.jsoup.select.Elements;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.io.Writer;

import java.util.regex.Pattern;


/**
* Example program to list links from a URL.
*/
public class SimpleWebCrawler {

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

Validate.isTrue(args.length == 0, "usage: supply url to fetch");

String url = "http://www.placeofjo.blogspot.com/";
print("Fetching %s...", url);


Document doc = Jsoup.connect(url).get();

Elements links = doc.select("a[href]");


System.out.println("\n");


for (Element link : links) {

print(" %s ", link.attr("abs:href"), trim(link.text(), 35));


}
}

private static void print(String msg, Object... args) {
System.out.println(String.format(msg, args));
}

private static String trim(String s, int width) {
if (s.length() > width)
return s.substring(0, width-1) + ".";
else
return s;
}


}

最佳答案

将您的代码修改为如下所示:

BufferedWriter bw = new BufferedWriter(new FileWriter(new File("/path/to/file/name.txt")));
for (Element link : links) {
bw.write("Link: " link.text().trim());
bw.write(System.getProperty("line.separator"));
}
bw.flush();
bw.close();

关于java - 将输出写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5144975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com