public static void main(String[] args) throws IOException {
for (int i=21;i<30;i++){
path="https://www.super.kg/media/audio/"+i;
Document dc = Jsoup.connect(path).timeout(6000).get();
Elements body = dc.select("div.clear");
for (Element item : body) {
String method = item.select("div.media_mtspan.video_desc_text").html();
method= method.replaceAll("<br>", "\n");
System.out.println(method);
PrintWriter writer = new PrintWriter("C:\\Users\\cholp\\Desktop\\out.txt", "UTF-8");
writer.println(method);
writer.close();
}
}
}
请帮助我,无法将变量“方法”写入文件。运行程序后,文件中没有任何内容
最佳答案
问题是这样的:
for (Element item : body) {
String method = item.select("div.media_mtspan.video_desc_text").html();
method = method.replaceAll("<br>", "\n");
System.out.println(method);
// Here
PrintWriter writer = new PrintWriter("C:\\Users\\cholp\\Desktop\\out.txt", "UTF-8");
writer.println(method);
writer.close();
}
PrintWriter(String fileName)
将使用以下代码构造一个 PrintWriter
实例:
public PrintWriter(String fileName) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
false);
}
默认情况下,FileOutputStream
会截断文件并打印内容(method
),因此最后一个 method
将在文件,并且最后一个方法恰好是空的,所以看起来写不通,但实际上确实可以,要解决这个问题,尝试替换 new PrintWriter("C:\\Users\\cholp\\Desktop\\out.txt", "UTF-8")
与 new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\Users\\cholp\\Desktop\\out.txt")、"UTF-8"))、/*append*/true)
,或者更好,将编写器从 for 循环中拉出:
PrintWriter writer = new PrintWriter("C:\\Users\\cholp\\Desktop\\out.txt", "UTF-8");
for (Element item : body) {
String method = item.select("div.media_mtspan.video_desc_text").html();
method = method.replaceAll("<br>", "\n");
System.out.println(method);
writer.append(method);
}
writer.close();
关于java - 在java中使用jsoup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49964262/