How can I normalize the EOL character in Java?

后端 未结 8 853
醉话见心
醉话见心 2020-12-29 03:13

I have a linux server and many clients with many operating systems. The server takes an input file from clients. Linux has end of line char LF, while Mac has end of line cha

8条回答
  •  被撕碎了的回忆
    2020-12-29 03:21

    Had to do this for a recent project. The method below will normalize the line endings in the given file to the line ending specified by the OS the JVM is running on. So if you JVM is running on Linux, this will normalize all line endings to LF (\n).

    Also works on very large files due to the use of buffered streams.

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

提交回复
热议问题