PrintWriter # println method does not work as expected

This code:

PrintWriter output = new PrintWriter(new FileWriter(outputFile, false)); output.println("something\n"); output.println("something else\n"); 

Outputs:

 something something else 

Instead:

 something something else 

I tried using "\ r \ n" instead of "\ n", but it just doesn't work the way I want it. How to fix it?

PS I use windows 7

+4
source share
5 answers

Your code works like a charm, just check the file using the appropriate programmer editor. (or, as I said earlier, take a look at the hex dump file)

+2
source

You can concatenate a newline to separate lines:

  String newLine = System.getProperty("line.separator"); output.println("something" + newLine); output.println("something else" + newLine); 
+6
source

it

 import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class Main { public static void main(String[] args) { PrintWriter output; try { output = new PrintWriter(new FileWriter("asdf.txt", false)); output.println("something\n"); output.println("something else\n"); output.close(); } catch (IOException e) { e.printStackTrace(); } } } 

Works well for me, I get asdf.txt like this

something

something else

I am using jre1.7, what are you using?

+2
source

This works great. You must use notepad for output. Try using a different text editor, such as Notepad ++. You will get the desired result.

+1
source

Try the following:

 package com.stackoverflow.works; import java.io.FileWriter; import java.io.PrintWriter; /* * @author: sarath_sivan */ public class PrintWriterExample { private static final String NEW_LINE = System.getProperty("line.separator"); public static void main(String[] args) { String outputFile = "C:/Users/sarath_sivan/Desktop/out.txt"; PrintWriter output = null; try { output = new PrintWriter(new FileWriter(outputFile, false)); output.println("something" + NEW_LINE); output.println("something else" + NEW_LINE); output.flush(); } catch(Exception exception) { exception.printStackTrace(); } finally { if (output != null) { output.close(); } } } } 

OUTPUT:

Output

0
source

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


All Articles