Search code examples
javafilewriterbufferedwriter

Write Strings that contain \n with BufferedWriter


If I have a String that contains some words with here and there a \n in between, is there a way to write them into a .txt file on separate lines? For example:

    File myFile = new File("TextFile.txt");
    FileWriter fw = null;
    try {
        fw = new FileWriter(myFile.getAbsoluteFile());
    } catch (IOException e) {
        e.printStackTrace();
    }
    BufferedWriter bw = new BufferedWriter(fw);
    try {
        bw.write(myString);
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

Where myString is something like:

"\nwords\nwords\nwords\n"

With this code I get in the text file words words words instead of

words 
words
words

Solution

  • You can either use an editor which understands \n as newline, or use this code:

    text = text.replaceAll("\n","\r\n");