Reputation: 25
Hi everyone I am trying to add a new line of string into an existing file, however the code i have appends it to the last string instead. I fixed it by adding a new line character to the string appending to the file, is there another way to append a string on a new line at the end of a file without adding the new line character to the beginning of the string?
String name = "\nbob";
BufferedWriter out = new BufferedWriter(new FileWriter("names.txt",true));
out.write(name);
out.close();
current file:
bill
joe
john
after append
bill
joe
john
bob
append without newline
bill
joe
johnbob
Upvotes: 0
Views: 2792
Reputation: 719
It is use Java 7. BufferedWritter class provide newLine() method for break new line. You can follow this example. example link
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterDemo {
//file path
private static final String FILENAME = "/home/farid/Desktop/bw.txt";
public static void main(String[] args) {
//BufferedWriter api //https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html
try(BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME))) {
String str = "This is the content to write into file";
//write method
bw.write(str);
//break new line
bw.newLine();
String seconStr = "This is the content to write into file.";
//write method
bw.write(seconStr);
//break new line
bw.newLine();
//console print message
System.out.println("Successfully compeleted");
//BufferedWritter close
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Upvotes: 0
Reputation: 140299
A \n
will be appended to your file here; but clearly you're just viewing it in such a way that you think there's no newline.
If you're working on Windows, \n
isn't the correct line separator: use \r\n
instead:
String name = "\r\nbob";
Windows uses \r\n
as its line separator; and tools like Notepad (still) don't handle non-Windows line endings correctly.
Note that using out.newLine()
is not necessarily the correct approach: this means that the current platform's line separator will be used. That might be correct; but if you're running this code on *nix, and the original file was generated on Windows (and has to continue to be readable correctly on Windows), it will not be, because \n
will be used. "Write once, run anywhere" doesn't quite work here.
Upvotes: 4