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

后端 未结 9 1439
星月不相逢
星月不相逢 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:30

    To be in phase with the BufferedReader class, you may use the following method that handles \n, \r, \n\r and \r\n end line separators:

    public static String retrieveLineSeparator(File file) throws IOException {
        char current;
        String lineSeparator = "";
        FileInputStream fis = new FileInputStream(file);
        try {
            while (fis.available() > 0) {
                current = (char) fis.read();
                if ((current == '\n') || (current == '\r')) {
                    lineSeparator += current;
                    if (fis.available() > 0) {
                        char next = (char) fis.read();
                        if ((next != current)
                                && ((next == '\r') || (next == '\n'))) {
                            lineSeparator += next;
                        }
                    }
                    return lineSeparator;
                }
            }
        } finally {
            if (fis!=null) {
                fis.close();
            }
        }
        return null;
    }
    

提交回复
热议问题