简体   繁体   English

使用jsoup将控制台输出写入文本文件

[英]write the console output to a text file using jsoup

I wanted to write the console output to a text file but somehow it only writes one line to my text file. 我想将控制台输出写入文本文件,但是不知何故,它只能将一行写入文本文件。 I am new to Java. 我是Java新手。 I don't understand the p in the code, so please help me. 我不理解代码中的p ,所以请帮助我。

Here is my code : 这是我的代码:

package htmlparser;
import java.io.IOException;
import java.util.logging.*;    
import org.jsoup.*;
import org.jsoup.nodes.*;
import org.jsoup.select.*;    
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.File;
import java.io.*;

public class Htmlparser {

  public static void main(String[] args)  {
    try {
      String url = "http://cell-phone-providers-review.toptenreviews.com/cingular-review.html";
      Document doc = Jsoup.connect(url).get();
      Elements paragraphs = doc.select("p");
      for(Element p : paragraphs)
        System.out.println(p.text());

      PrintWriter out = new PrintWriter(new FileWriter("C:/Users/Desktop/outputtext.txt")); 
      out.print(System.in); 
      out.close();          
    } 
    catch (IOException ex) {
      Logger.getLogger(Htmlparser.class.getName())
            .log(Level.SEVERE, null, ex);
    }
  }
}

You are opening your file inside the for loop so only the most recent line gets written as the file is overridden each time. 您正在for循环中打开文件,因此每次写入文件时都会覆盖最新行。 Open your file outside the for loop and close it after the loop. 在for循环外打开文件,然后在循环后关闭它。

public static void main(String[] args) {
    try {
        String url = "http://cell-phone-providers-review.toptenreviews.com/cingular-review.html";
        Document doc = Jsoup.connect(url).get();
        Elements paragraphs = doc.select("p");
        PrintWriter out = new PrintWriter(new FileWriter("C:/Users/Desktop/outputtext.txt")); 
        for(Element p : paragraphs) {
            out.print(p.text());
        }
        out.close();          
    } catch (IOException ex) {
        Logger.getLogger(Htmlparser.class.getName()).log(Level.SEVERE, null, ex);
    }
}

You don't have any braces surrounding your loop so this statement is the only one invoked inside the loop 您的循环没有大括号,因此此语句是循环内唯一调用的语句

System.out.println(p.text());

Create the PrintWriter before entering the loop and use out.print(System.in) to write the console output to file. 进入循环之前,请创建PrintWriter并使用out.print(System.in)将控制台输出写入文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM