cha*_*cko 12 java bufferedreader linefeed java-io
我正在通过BufferedReader读取文件
String filename = ...
br = new BufferedReader( new FileInputStream(filename));
while (true) {
String s = br.readLine();
if (s == null) break;
...
}
Run Code Online (Sandbox Code Playgroud)
我需要知道线条是否以'\n'或'\ r \n'分隔是否有我能找到的方法?
我不想打开FileInputStream以便最初扫描它.理想情况下,我想询问BufferedReader,因为它必须知道.
我很高兴覆盖BufferedReader来破解它,但我真的不想打开文件流两次.
谢谢,
注意:当前行分隔符(由System.getProperty("line.separator")返回)无法使用,因为该文件可能已由另一个应用程序在另一个操作系统上写入.
Ant*_*ine 11
要与BufferedReader类同步,您可以使用以下方法来处理\n,\ r,\n\r和\ r \n结束行分隔符:
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;
}
Run Code Online (Sandbox Code Playgroud)
在阅读了java文档(我承认自己是一个pythonista)之后,似乎没有一种干净的方法来确定特定文件中使用的行端编码.
我建议的最好的事情是你使用BufferedReader.read()并迭代文件中的每个字符.像这样的东西:
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 = "";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22600 次 |
| 最近记录: |