What is the problem: I don’t know how to save the data from the List to the .txt file. it saves the data correctly, I can refer to the List elements, they are displayed on the screen. But how to save the whole thing in a text file?

public static void parser() throws IOException { List<Neews> news = new ArrayList<>(); Document doc = Jsoup.connect("http://").get(); Elements trElements = doc.getElementsByAttributeValue("class", "con_title"); trElements.forEach(trElement -> { Elements elementsByClass = trElement.getElementsByClass("con_title"); String name = elementsByClass.get(0).text(); news.add(new Neews(name)); }); news.forEach(System.out::println); } 
  • I'm thinking that if you just convert a List into a regular array and save it with a regular Writer? - Marat Zimnurov

2 answers 2

I do not know the constructor of the Neews class; let's say we need to pass the first and last name into it. Also assume that this class has getName() methods for getting the first name and getFamily() for the last name.

 List<Neews> list = new ArrayList<>(); //здесь, заместо комментария, вы заполняете ArrayList или как там у вас, вообщем после этого он у вас содержит данные FileWriter writer = new FileWriter("output.txt"); for(Neews news : list { String name = news.getName(); String family = news.getFamily(); writer.write(name + " " + family + System.getProperty("line.separator")); } writer.close(); 

As a result, the file output.txt will contain the names and surnames separated by spaces. And pairs of FIs will be divided by the translation on the next line.

  • Perfectly! Now I will look, and in the Neews class there is one field - name. Forgive me for not throwing him off) didn’t think something) - Marat Zimnurov
  • getName() is there? - Flippy
  • If only one field, then why do you need a class at all? You can use the regular ArrayList - Flippy
  • it does not matter) in general, he does not tolerate the next line, I don’t understand why it goes like this ( - Marat Zimnurov
  • Updated the answer. Take a look - Flippy

Write to the file line by line, you can like this:

 List<String> lines = Arrays.asList("hello", "world"); Files.write(Paths.get("demo.txt"), lines, StandardOpenOption.CREATE); 
  • What kind of class is that? Files - Flippy
  • @ SergeyGrushin java.nio.file.Files . - Regent
  • Did not look into this package, java.nio . Apparently actively use it - Flippy