Reputation: 115
I want to write text into a file and everytime I do it should make a new line. I've seen many answers to this question being just "use \n" but that doesn't work for me.
This is the code I used:
File file = new File("C:\\Users\\Schule\\IdeaProjects\\projectX\\src\\experiment\\input.txt");
boolean result;
if(!file.exists()) {
try {
// create a new file
result = file.createNewFile();
// test if successfully created a new file
if(result) {
System.out.println("Successfully created " + file.getCanonicalPath());
}
} catch (IOException e) {
e.printStackTrace();
}
}
String output = name + ": " + highscoreString + "\n";
try {
PrintWriter out = new PrintWriter(new FileWriter(file, true));
out.append(output);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
The code I have writes the new Highscore and the name of the person who made it in a file. It works perfectly fine except that it writes everything on a line like this for example: Nicola: Your highscore is 10 secondsThomas: Your highscore is 11 seconds But I want: Nicola: Your highscore is 10 seconds Thomas: Your highscore is 11 seconds
I know there are some other things I need to fix and improve but right now, this is my biggest problem. Does anyone know what to do? (sorry for my name btw ;)
Upvotes: 1
Views: 1301
Reputation: 1644
Windows and Linux line breaks are different. Try to write \r\n
.
EDIT
If you use System.lineSeparator()
to get line break it will give platform based line break. So if you create a file on unix and send it to windows users they will see that file like one line. But if you are using windows os to create file, linux users will see file correct.
Upvotes: 5
Reputation: 2397
You need to do: out.write(System.getProperty("line.separator"));
System.getProperty("line.separator")
will give you the line separator for your platform (whether Windows/Linux/..).
Upvotes: 6