使用 BufferedWriter 写入包含 \n 的字符串

Write Strings that contain \n with BufferedWriter

如果我有一个字符串,其中包含一些单词,中间有一个 \n, 有没有办法将它们写入不同行的 .txt 文件?例如:

    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();
    }

其中 myString 类似于:

"\nwords\nwords\nwords\n"

使用此代码,我进入文本文件 words words words 而不是

words 
words
words

您可以使用将 \n 理解为换行符的编辑器,或者使用此代码:

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