我如何规范Java中的EOL字符?

我有一个Linux服务器和许多操作系统的客户端。 服务器从客户端获取输入文件。 Linux的行尾有char LF,而Mac的行尾是char CR,而Windows的行结束是char CR + LF

服务器需要行尾字符LF。 使用java,我想确保该文件将始终使用linux eol char LF。 我怎样才能实现它?


结合两个答案(Visage&eumiro):

编辑:在阅读评论后。 线。 System.getProperty(“line.separator”)没有用。
在将文件发送到服务器之前,请打开它,替换所有EOL和回写
确保使用DataStream来完成,并用二进制编写

String fileString;
//..
//read from the file
//..
//for windows
fileString = fileString.replaceAll("rn", "n");
fileString = fileString.replaceAll("r", "n");
//..
//write to file in binary mode.. something like:
DataOutputStream os = new DataOutputStream(new FileOutputStream("fname.txt"));
os.write(fileString.getBytes());
//..
//send file
//..

replaceAll方法有两个参数,第一个是要替换的字符串,第二个是替换字符串。 但是,第一个被视为一个正则表达式,所以''就是这样解释的。 所以:

"rn" is converted to "rn" by Regex
"rn" is converted to CR+LR by java

你可以试试吗?

content.replaceAll("rn?", "n")

必须为最近的项目做到这一点。 下面的方法会将给定文件中的行尾标准化为由JVM运行的操作系统指定的行。 因此,如果您的JVM在Linux上运行,则会将所有行尾标准化为LF( n)。

由于使用缓冲流,它也适用于非常大的文件。

public static void normalizeFile(File f) {      
    File temp = null;
    BufferedReader bufferIn = null;
    BufferedWriter bufferOut = null;        

    try {           
        if(f.exists()) {
            // Create a new temp file to write to
            temp = new File(f.getAbsolutePath() + ".normalized");
            temp.createNewFile();

            // Get a stream to read from the file un-normalized file
            FileInputStream fileIn = new FileInputStream(f);
            DataInputStream dataIn = new DataInputStream(fileIn);
            bufferIn = new BufferedReader(new InputStreamReader(dataIn));

            // Get a stream to write to the normalized file
            FileOutputStream fileOut = new FileOutputStream(temp);
            DataOutputStream dataOut = new DataOutputStream(fileOut);
            bufferOut = new BufferedWriter(new OutputStreamWriter(dataOut));

            // For each line in the un-normalized file
            String line;
            while ((line = bufferIn.readLine()) != null) {
                // Write the original line plus the operating-system dependent newline
                bufferOut.write(line);
                bufferOut.newLine();                                
            }

            bufferIn.close();
            bufferOut.close();

            // Remove the original file
            f.delete();

            // And rename the original file to the new one
            temp.renameTo(f);
        } else {
            // If the file doesn't exist...
            log.warn("Could not find file to open: " + f.getAbsolutePath());
        }
    } catch (Exception e) {
        log.warn(e.getMessage(), e);
    } finally {
        // Clean up, temp should never exist
        FileUtils.deleteQuietly(temp);
        IOUtils.closeQuietly(bufferIn);
        IOUtils.closeQuietly(bufferOut);
    }
}
链接地址: http://www.djcxy.com/p/78441.html

上一篇: How can I normalize the EOL character in Java?

下一篇: Output stream over a StringBuilder