How to Write New Line Character to a File in Java

write newline into a file

To write text (rather than raw bytes) to a file you should consider using FileWriter. You should also wrap it in a BufferedWriter which will then give you the newLine method.

To write each word on a new line, use String.split to break your text into an array of words.

So here's a simple test of your requirement:

public static void main(String[] args) throws Exception {
String nodeValue = "i am mostafa";

// you want to output to file
// BufferedWriter writer = new BufferedWriter(new FileWriter(file3, true));
// but let's print to console while debugging
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

String[] words = nodeValue.split(" ");
for (String word: words) {
writer.write(word);
writer.newLine();
}
writer.close();
}

The output is:

i
am
mostafa

How to add a new line of text to an existing file in Java?

you have to open the file in append mode, which can be achieved by using the FileWriter(String fileName, boolean append) constructor.

output = new BufferedWriter(new FileWriter(my_file_name, true));

should do the trick

keeping newline characters when writing a file

You can replace every escape sequence with a double-backslash:

public static String escapeChars(String str) {
char[][] escapes = {
{ '\n', 'n' },
{ '\r', 'r' },
{ '\f', 'f' },
{ '\b', 'b' },
{ '\t', 't' }
};
for (char[] escape : escapes) {
str = str.replaceAll(Character.toString(escape[0]), "\\\\" + escape[1]);
}
return str;
}

Double- and single-apostrophe escaping can be added easily, but I've omitted it in this answer.

Inserting New Lines when Writing to a Text File in Java

To create new lines, simply append a newline character to the end of the string:

FileWriter writer = ...
writer.write("The line\n");

Also, the PrintWriter class provides methods which automatically append newline characters for you (edit: it will also automatically use the correct newline string for your OS):

PrintWriter writer = ...
writer.println("The line");


Related Topics



Leave a reply



Submit