KingKeyy
KingKeyy

Reputation: 59

Java does not recognise newline \n in log file on one computer

I have this code for writing a log of outcomes into a txt file

aWriter.write(date + ";" + outcome + ";" + var2 + ";" + var + ";" + time + ";" + code + "\n");

When i open the log.txt file on my computer everything is as it's supposed to be, example:

> 2018-12-17;OK;456;456;14:0:9;123456
> 2018-12-17;OK;487;487;14:0:13L123456
> 2018-12-17;OK;456987;456987;14:0:20;123456
> 2018-12-18;NOK;3;123;8:51:12;123456

But, when i open this log file on a different computer that the program is running in i get this result:

2018-12-17;OK;456;456;14:0:9;1234562018-12-17;OK;487;487;14:0:13L1234562018-12-17;OK;456987;456987;14:0:20;1234562018-12-18;NOK;3;123;8:51:12;123456

What is the cause for this? is this My code or just some Windows default settings?

Upvotes: 2

Views: 622

Answers (1)

Mark
Mark

Reputation: 5239

Not every system uses the same line endings (and some text editor expect \r\n instead of \n since that's the platform-specific line separator for windows), you may use %n using some sort of Formatter:

'n' the platform-specific line separator as returned by System.getProperty("line.separator").

Like this using String#format:

aWriter.write(
        String.format("%s%n", String.join(";", date, outcome, var2, var, time, code)));
//                       ^ %s prints the string, %n the line ending

Or more like your original code (without %n):

aWriter.write(String.join(";", date, outcome, var2, var, time, code) 
        + System.getProperty("line.separator"));

Alternatively

You can configure what line endings your text editor will look for, this configuration is specific to your text editor of choice.

I've done a small test, if you want to keep using Notepad use the first solution, it will render files correctly if you use the correct line endings. Otherwise Notepad++ will be able to read your file as is.

Upvotes: 2

Related Questions