我想将以下输出写入文本文件。我知道这很容易,但我想我忘记了一些基础知识。
我尝试使用'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;
}
}
答案 0 :(得分:3)
将您的代码修改为:
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();
答案 1 :(得分:2)
您需要的一切都在这里:http://www.exampledepot.com/egs/java.io/WriteToFile.html
try {
BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
out.write("aString");
out.close();
} catch (IOException e) {
}
答案 2 :(得分:0)
查看java.io.FileWriter