How to find out which line separator BufferedReader#readLine() used to split the line?

后端 未结 9 1441
星月不相逢
星月不相逢 2020-12-11 01:47

I am reading a file via the BufferedReader

String filename = ...
br = new BufferedReader( new FileInputStream(filename));
while (true) {
   String s = br.re         


        
9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 02:33

    Not sure if useful, but sometimes I need to find out the line delimiter after I've read the file already far-down the road.

    In this case I use this code:

    /**
    * 

    Identify which line delimiter is used in a string

    * * This is useful when processing files that were created on different operating systems. * * @param str - the string with the mystery line delimiter. * @return the line delimiter for windows, {@code \r\n},
    * unix/linux {@code \n} or legacy mac {@code \r}
    * if none can be identified, it falls back to unix {@code \n} */ public static String identifyLineDelimiter(String str) { if (str.matches("(?s).*(\\r\\n).*")) { //Windows //$NON-NLS-1$ return "\r\n"; //$NON-NLS-1$ } else if (str.matches("(?s).*(\\n).*")) { //Unix/Linux //$NON-NLS-1$ return "\n"; //$NON-NLS-1$ } else if (str.matches("(?s).*(\\r).*")) { //Legacy mac os 9. Newer OS X use \n //$NON-NLS-1$ return "\r"; //$NON-NLS-1$ } else { return "\n"; //fallback onto '\n' if nothing matches. //$NON-NLS-1$ } }

提交回复
热议问题