I am reading a text file using BufferedReader.readLine()
in java. My text file was created with hidden line breaks. My question is I need to skip carriage return (\r
) as line break, only need to consider line feed (\n
) as line breaker.
我正在使用java中的BufferedReader.readLine()读取文本文件。我的文本文件是使用隐藏换行符创建的。我的问题是我需要跳过回车符(\ r)作为换行符,只需要考虑换行符(\ n)作为换行符。
How can I achieve this?
我怎样才能做到这一点?
2 个解决方案
#1
2
You have to write your own readLine
. BufferedReader.readLine
will consider all \r, \n and \r\n as line breaks and you cannot change it. Make a helper where you define your own line breaks.
你必须编写自己的readLine。 BufferedReader.readLine将所有\ r,\ n和\ r \ n视为换行符,您无法更改它。在你定义自己的换行符的地方做一个帮手。
Edit: could look like this
编辑:看起来像这样
String readLineIgnoreCR(BufferedReader reader)
{
int c = reader.read();
String line = "";
while(c >= 0)
{
if((char) c == '\r')
continue;
else if((char) c == '\n')
return line;
line += (char) c;
}
}
#2
1
Is correct:
String readLineIgnoreCR(BufferedReader reader) {
int c = 0;
String line = "";
while(c >= 0) {
c = reader.read();
if((char) c == '\r')
continue;
else if((char) c == '\n')
return line;
line += (char) c;
}
return line;
}
#1
2
You have to write your own readLine
. BufferedReader.readLine
will consider all \r, \n and \r\n as line breaks and you cannot change it. Make a helper where you define your own line breaks.
你必须编写自己的readLine。 BufferedReader.readLine将所有\ r,\ n和\ r \ n视为换行符,您无法更改它。在你定义自己的换行符的地方做一个帮手。
Edit: could look like this
编辑:看起来像这样
String readLineIgnoreCR(BufferedReader reader)
{
int c = reader.read();
String line = "";
while(c >= 0)
{
if((char) c == '\r')
continue;
else if((char) c == '\n')
return line;
line += (char) c;
}
}
#2
1
Is correct:
String readLineIgnoreCR(BufferedReader reader) {
int c = 0;
String line = "";
while(c >= 0) {
c = reader.read();
if((char) c == '\r')
continue;
else if((char) c == '\n')
return line;
line += (char) c;
}
return line;
}