Strings written to file do not preserve line breaks

Text from a JTextArea will have \n characters for newlines, regardless of the platform it is running on. You will want to replace those characters with the platform-specific newline as you write it to the file (for Windows, this is \r\n, as others have mentioned).

I think the best way to do that is to wrap the text into a BufferedReader, which can be used to iterate over the lines, and then use a PrintWriter to write each line out to a file using the platform-specific newline. There is a shorter solution involving string.replace(...) (see comment by Unbeli), but it is slower and requires more memory.

Here is my solution – now made even simpler thanks to new features in Java 8:

public static void main(String[] args) throws IOException {
    String string = "This is lengthy string that contains many words. So\nI am wrapping it.";
    System.out.println(string);
    File file = new File("C:/Users/User/Desktop/text.txt");

    writeToFile(string, file);
}

private static void writeToFile(String string, File file) throws IOException {
    try (
        BufferedReader reader = new BufferedReader(new StringReader(string));
        PrintWriter writer = new PrintWriter(new FileWriter(file));
    ) {
        reader.lines().forEach(line -> writer.println(line));
    }
}

Leave a Comment