Insert line break when writing to file?

So my code looks like this:

try { while ((line = br.readLine()) != null) { Matcher m = urlPattern.matcher (line); while (m.find()) { System.out.println(m.group(1)); //the println puts linebreak after each find String filename= "page.txt"; FileWriter fw = new FileWriter(filename,true); fw.write(m.group(1)); fw.close(); //the fw writes everything after each find with no line break } } 

I get the correct output form in the line System.out.println(m.group(1)); However, when I later want to write what is shown m.group(1) It writes to a file without placing a line, since the code does not have this.

+4
source share
4 answers

Just call fw.write(System.getProperty("line.separator")); .

System.getProperty("line.separator") will provide you with a line separator for your platform (whether it be Windows or some kind of Unix flavor).

+20
source

just

 fw.write("\n"); 

which will put the escape character for the new line

+1
source

println(text) adds a line break to a line and essentially matches print(text); print(System.getProperty("line.separator")); print(text); print(System.getProperty("line.separator")); .

So, to add a line break, you have to do the same.

However, to improve the code, I have two recommendations:

  • Do not create a new FileWriter in a loop. Create it outside of the loop and close it after the loop.
  • Do not use FileWriter , but instead PrintWriter wrapped around FileWriter . Then you get the same println() method as System.out .
+1
source

Instead, you can use System.getProperty ("line.separator") and System.lineSeparator ()

0
source

Source: https://habr.com/ru/post/1492014/


All Articles