I understand that the BufferedWriter
stores the information before I write in in a file before executing the act of writing it in a file using flush()
, Append()
etc..
I gather information from multiple sources, so currently what I am doing is looping in each source and appending it directly to the file each time, but what I'm trying to accomplish is to add all the information in the BufferedWriter
and after finishing the loop, writing it to the file, how could that be done?
I am trying to improve performance by not flushing the data into the file so many times. The performance is issue because this might loop 1 million times.
Here is what I'm currently doing:
- Open
BufferedWriter
- read data from a different source and storing in the buffer
- appending stored data in a text file(here the buffer is emptied)
- repeating steps 2.- and 3.- 50 times
- closing text file
Here is what I'm trying to do:
- Open
BufferedWriter
- read data from a different source and storing in the buffer
- repeat step 2.- 50 times
- append all the data collected(the data gathered over the 50 loops)
- close the file
here is the code.
for (int mainLoop = 0; mainLoop < 50; mainLoop++){
try {
BufferedWriter writer = writer = new BufferedWriter(new
FileWriter
("path to file in computer" + mainLoop + ".txt", true));
for(int forloop = 0; forloop < 50; forloop++) {
final Document pageHtml=
Jsoup.connect("link to a page").get();
Elements body = pageHtml.select("p");
writer.append(System.getProperty("line.separator"));
writer.append(System.getProperty("line.separator"));
writer.append(body.text());
System.out.println(forloop);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}continue;
}