有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用BufferReader“\n”读取后的java不会被接受为新行字符,如何解决此问题?

我有一个大的文本文件,我想格式化。假设输入文件名为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);
    }

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

更容易看出的是,我希望我的输入文件中有

work\n
work

和输出为

work 
work

我正在使用mac,因此分隔符应为“\n”


共 (2) 个答案

  1. # 1 楼答案

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

    work \nwork
    

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

  2. # 2 楼答案

    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值添加到文件中。此字符不可显示,因此您无法在文件中看到它