Search code examples
javajsoup

Jsoup java rewrites the file string which it should add


code that should read html file and write the result another file the buffered writer writes the file but when the code is run with different urlit doesn't appends but rewrites the file and the previous content disappears

the solution recuired is that when jsoup iterates new html the result should add to output file and not rewrite

changed different writer types other than buffered writer

public class WriteFile 
{
    public static void main(String args[]) throws IOException
  { 
    String url = "http://www.someurl.com/registers";
    Document doc = Jsoup.connect(url).get();
    Elements es = doc.getElementsByClass("a_code");     

    for (Element clas : es) 
    {                    
      System.out.println(clas.text()); 
      BufferedWriter writer = new BufferedWriter(new FileWriter("D://Author.html"));
      writer.append(clas.text());
      writer.close();
    } 
  }    
}

Solution

  • Don't mistake the append-method of the BufferedWriter as appending content to the file. It actually appends to the given writer.

    To actually append additional content to the file you need to specify that when opening the file writer. FileWriter has an additional constructor parameter allowing to specify that:

    new FileWriter("D://Author.html", /* append = */ true)
    

    You may even be interested in the Java Files API instead, so you can spare instantating your own BufferedWriter, etc.:

    Files.write(Paths.get("D://Author.html"), clas.text().getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    

    Your loop and what you are writing may further be simplifiable to something as follows (you may then even omit the APPEND-open option again, if that makes sense):

    Files.write(Paths.get("D://Author.html"), 
                String.join("" /* or new line? */, 
                            doc.getElementsByClass("a_code")
                               .eachText()
                           ).getBytes(), 
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);