0

I'm trying to print a multiple-line String into a PrintWriter, but it doesn't recognizes the different lines.

I have this String: "2\n0 0 1 string1\n0 2 1 string2".

The text I expected to have into the file was:

2
0 0 1 string1
0 2 1 string2

but it actually is:

20 0 1 string10 2 1string2

My code is:

 public void save(String str){
    try{
        PrintWriter out = new PrintWriter("file.txt");
        out.println(str);
        out.close();
        System.out.print(str);
    }catch(Exception e){System.out.println(e);}
}

It's printed OK in the console.

I'm using BlueJ to code. My OS is W7 and I just opened the file with notepad.

SOLVED!

Using "\r\n" instead of just "\n" works properly!

Makoto
  • 104,088
  • 27
  • 192
  • 230
Joan
  • 31
  • 5

2 Answers2

3

If you want represent literal newlines on Windows, you need to use \r\n, which is the standard delimiter for that platform.

In other words, your original string needs to be

"2\r\n0 0 1 string1\r\n0 2 1 string2"

However, this quickly becomes non-portable, so you should instead query for the standard delimiter first and then use it to construct your string.

String d = System.getProperty("line.separator");
String mystr = String.format("2%s0 0 1 string1%s0 2 1 string2", d, d)

Moreover, based on this answer, we can use %n format specifier to avoid the call to getProperty().

String mystr = String.format("2%n0 0 1 string1%n0 2 1 string2")
Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • Shouldn't that be `%n`, not `%%n` on the last two lines? So `String.format("2%n0 0 1 string1%n0 2 1 string2")` with no need for `d` any more? – Dawood ibn Kareem Jun 25 '14 at 02:28
  • @davidwallace I grabbed that from the linked question. I'll update later if I test and it's wrong. I removed the d though. – merlin2011 Jun 25 '14 at 02:33
  • Yeah, the answer you took that from says "use `%n`". It seems you misread it. – Dawood ibn Kareem Jun 25 '14 at 03:10
  • @DavidWallace, I just got to my computer and tested it and you are correct. My answer has now been edited with the correction. It appears that I misread the example in the answer. – merlin2011 Jun 25 '14 at 03:56
1

From the PrintWriter.println() javadoc,

Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').

So, I think you could use -

try{
  PrintWriter out = new PrintWriter("file.txt");
  for (String s : str.split("\n")) {
    out.println(s);
  }
  out.close();
  System.out.print(str);
}catch(Exception e){System.out.println(e);}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 2
    @JoanPuicgerver: Please consider that `\r\n` is only the proper line terminator for windows. Do not needlessly introduce OS dependencies. – Deduplicator Jun 25 '14 at 01:42