How can I normalize the EOL character in Java?

后端 未结 8 981
醉话见心
醉话见心 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条回答
  •  猫巷女王i
    2020-12-29 03:37

    Although String.replaceAll() is simpler to code, this should perform better since it doesn't go through the regex infrastructure.

        /**
     * Accepts a non-null string and returns the string with all end-of-lines
     * normalized to a \n.  This means \r\n and \r will both be normalized to \n.
     * 

    * Impl Notes: Although regex would have been easier to code, this approach * will be more efficient since it's purpose built for this use case. Note we only * construct a new StringBuilder and start appending to it if there are new end-of-lines * to be normalized found in the string. If there are no end-of-lines to be replaced * found in the string, this will simply return the input value. *

    * * @param inputValue !null, input value that may or may not contain new lines * @return the input value that has new lines normalized */ static String normalizeNewLines(String inputValue){ StringBuilder stringBuilder = null; int index = 0; int len = inputValue.length(); while (index < len){ char c = inputValue.charAt(index); if (c == '\r'){ if (stringBuilder == null){ stringBuilder = new StringBuilder(); // build up the string builder so it contains all the prior characters stringBuilder.append(inputValue.substring(0, index)); } if ((index + 1 < len) && inputValue.charAt(index + 1) == '\n'){ // this means we encountered a \r\n ... move index forward one more character index++; } stringBuilder.append('\n'); }else{ if (stringBuilder != null){ stringBuilder.append(c); } } index++; } return stringBuilder == null ? inputValue : stringBuilder.toString(); }

提交回复
热议问题