如何找出用于分割线的BufferedReader#readLine()哪个行分隔符? [英] How to find out which line separator BufferedReader#readLine() used to split the line?

查看:634
本文介绍了如何找出用于分割线的BufferedReader#readLine()哪个行分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过BufferedReader读取文件

I am reading a file via the BufferedReader

String filename = ...
br = new BufferedReader( new FileInputStream(filename));
while (true) {
   String s = br.readLine();
   if (s == null) break;
   ...
}

我需要知道这些线是否分开通过'\ n'或'\\\\''
有没有办法找到答案?

I need to know if the lines are separated by '\n' or '\r\n' is there way I can find out ?

我不想打开FileInputStream以便最初扫描它。
理想情况下,我想询问BufferedReader,因为它必须知道。

I don't want to open the FileInputStream so to scan it initially. Ideally I would like to ask the BufferedReader since it must know.

我很乐意覆盖BufferedReader来破解它,但我真的不想打开文件流两次。

I am happy to override the BufferedReader to hack it but I really don't want to open the filestream twice.

谢谢,

注意:当前行分隔符(由System.getProperty(line.separator)返回)不能用作文件可能是由另一个应用程序在另一个操作系统上编写的。

推荐答案

阅读 java docs (我承认自己是一名pythonista),它似乎没有一种干净的方法来确定特定文件中使用的行端编码。

After reading the java docs (I confess to being a pythonista), it seems that there isn't a clean way to determine the line-end encoding used in a specific file.

我建议的最好的方法是使用 BufferedReader.read()并迭代文件中的每个字符。这样的事情:

The best thing I can recommended is that you use BufferedReader.read() and iterate over every character in the file. Something like this:

String filename = ...
br = new BufferedReader( new FileInputStream(filename));
while (true) {
   String l = "";
   Char c = " ";
   while (true){
        c = br.read();
        if not c == "\n"{
            // do stuff, not sure what you want with the endl encoding
            // break to return endl-free line
        }
        if not c == "\r"{
            // do stuff, not sure what you want with the endl encoding
            // break to return endl-free line
            Char ctwo = ' '
            ctwo = br.read();
            if ctwo == "\n"{
                // do extra stuff since you know that you've got a \r\n
            }
        }
        else{
            l = l + c;
        }
   if (l == null) break;
   ...
   l = "";
}

这篇关于如何找出用于分割线的BufferedReader#readLine()哪个行分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆