在java中使用jsoup

时间:2018-04-22 09:02:39

标签: java jsoup

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

            } 
}
请帮助我,不能将变量“方法”写入文件。运行程序后,文件中没有任何内容

1 个答案:

答案 0 :(得分:1)

问题在于:

    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将在文件中打印,最后{{1}碰巧是空的,所以写作似乎不起作用但实际上确实如此,为了解决问题,尝试用method替换new PrintWriter("C:\\Users\\cholp\\Desktop\\out.txt", "UTF-8"),或者更好,将编写器拉出for循环:< / p>

new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\Users\\cholp\\Desktop\\out.txt"), "UTF-8")), /*append*/ true)