Reputation: 3
I have the following code:
FileWriter filewriter = null;
try { filewriter = new FileWriter("outUser.txt", true); }
catch (IOException e1) { e1.printStackTrace(); }
try {
filewriter.write(s1+"\n");
filewriter.flush();
}
catch (IOException e1) { e1.printStackTrace(); }
Its supposed to write on outUser
file the s1 string
and a newline. It only writes s1
, the newline is not written. I also tried with a new string that equals \n
and append it to s1
when written but still didn't work. Do any of you have some answers for me?
Upvotes: 0
Views: 81
Reputation: 32787
Different OS have different ways to represent newlines.
For Example,\n
is used in UNIX but \r\n
is used in Windows.
This answers why windows uses \r
You can use System.lineSeparator() which returns the system-dependent line separator string.
Upvotes: 2
Reputation: 2064
Do like this
FileWriter filewriter = null;
try {
filewriter = new FileWriter("c:\\outUser.txt", true);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
filewriter.write("hi"+System.getProperty("line.separator"));
filewriter.write("asd");
filewriter.flush();
}
catch (IOException e1) {
e1.printStackTrace();
}
Use Line Separator Property to print nextline to File .
Upvotes: 0
Reputation: 1376
The following should work
FileWriter filewriter = null;
try {
filewriter = new FileWriter("outUser.txt", true);
BufferedWriter buffWriter = new BufferedWriter(fileWriter);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
buffwriter.write(s1+"\n");
buffWriter.newLine();
buffwriter.flush();
}
catch (IOException e1) {
e1.printStackTrace();
}
Upvotes: 0
Reputation: 7166
Open your outUser.txt
with an text editor like notepad++ and enable the 'non-printable'-chars. You should see an CR/LF
, which is the \n
.
Upvotes: 0
Reputation: 4974
The line feed should be there, but keep in mind that different OS-es have different new line characters.
If you're out of luck you can always try BufferedWriter.newLine()
.
Upvotes: 2