使用 BufferReader 读取后 '\n' 不会被接受为新行字符,如何解决这个问题?

After reading with BufferReader '\n' won't be accepted as a new line char, how to solve this?

我有一个大文本文件要格式化。假设输入文件名为 inputFile,输出文件名为 outputFile.

这是我使用 BufferedReaderBufferedWriter 的代码 这是我的代码

 public static void readAndWrite(String fileNameToRead, String fileNameToWrite) {
        try{
            BufferedReader fr = new BufferedReader(
                    new FileReader(String.format("%s.txt", fileNameToRead)));
            BufferedWriter out = new BufferedWriter(
                    new FileWriter(String.format("%s.txt", fileNameToWrite), true));
            String currentTmp = "";
            String tmp = "";

            String test = "work \nwork";
            out.append(test);


            while((tmp = fr.readLine()) != null) {
                tmp = tmp.trim();
                if(tmp.isEmpty()) {
                    currentTmp = currentTmp.trim();
                    out.append(currentTmp);
                    out.newLine();
                    out.newLine();
                    currentTmp = "";
                } else {
                    currentTmp = currentTmp.concat(" ").concat(tmp);
                }
            }
            if(!currentTmp.equals("")) {
                out.write(currentTmp);
            }
            fr.close();
            out.close();
        } catch (IOException e) {
            System.out.println("exception occoured" + e);
        }

    }

    public static void main(String[] args) {
        String readFile = "inPutFile";
        String writeFile = "outPutFile";
        readAndWrite(readFile, writeFile);
    }

问题是代码中的test字符串中有'\n'的我们可以用BufferedWriter换行。但是,如果我将相同的字符串放入文本文件中,它不会执行相同的操作。

更简单的方法是我希望我的输入文件有这个

work\n
work

并输出为

work 
work

我用的是mac,所以分隔符应该是'\n'

work\n 

如果您在文件中看到“\n”,则它不是换行符。就两个字。

trim() 方法不会删除这些字符。

相反,你可能有类似的东西:

if (tmp.endsWith("\n")
    tmp = tmp.substring(0, tmp.length() - 2);

I am using mac, so the separator should be '\n'

您应该为平台使用换行符。所以当写入你的文件时,代码应该是:

} else {
    currentTmp = currentTmp.concat(" ").concat(tmp);
    out.append( currentTmp );
    out.newLine();
}

newline() 方法将为平台使用适当的换行字符串。

编辑:

您需要了解 Java 中的转义字符是什么。当您使用:

String text = "test\n"

并将字符串写入文件,只有 5 个字符写入文件,而不是 6 个。"\n" 是一个转义序列,它将导致新行字符的 ascii 值被添加到文件。此字符不可显示,因此您无法在文件中看到它。

@camickr 回答后,我想我意识到了问题所在。一些如果我在文件中有这样的文本如何

work \nwork

\n 不会被视为单个字符 ('\n'),而是被视为两个字符。我认为这就是为什么 BufferWriter 写入输入字符串时不会将其视为新行的原因。