BufferedReader的mark方法倒是很牛,只是这个参数到不是很好控制,网上讨论的也比较多
现在有这样一个需求
一个文本文件有如下四行内容
aaaa
bbbbb
=b
cccccc
我要用程序读取这个文件
但是第三行"=b"实际上是第二行的续行,也就是遇到行首是"="字符的就把该行和上行连接起来
也就是读出来是这种效果
aaaa
bbbbb=b
cccccc
我现在有段代码,但对它mark测试下行是不是"="打头的时候,如果这行是文件最后一行了,就IOException了
想了很久也没有搞定
原因就是读的line已经是最后一行了,下行已经是null了,对他进行mark,就会有问题了
现在暂时的解决办法是把reader.reset();用try catch包起来,遇到异常了不管,罪恶啊,罪恶
变成:
哪位高人能指点下我啊,多谢 :arrow:
或者把ch声明提前,在最后一个reset的时候判断ch是否读出了值
现在有这样一个需求
一个文本文件有如下四行内容
aaaa
bbbbb
=b
cccccc
我要用程序读取这个文件
但是第三行"=b"实际上是第二行的续行,也就是遇到行首是"="字符的就把该行和上行连接起来
也就是读出来是这种效果
aaaa
bbbbb=b
cccccc
我现在有段代码,但对它mark测试下行是不是"="打头的时候,如果这行是文件最后一行了,就IOException了
想了很久也没有搞定
public static void markLine() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File(
"in.txt")));
for (String line = reader.readLine(); line != null; line = reader
.readLine()) {
reader.mark(1);
for (int ch = reader.read(); ch == (int) ' ' || ch == (int) '\t'
|| ch == (int) '='; ch = reader.read()) {
reader.reset();
String newLine = reader.readLine();
if (newLine != null)
line += newLine;
reader.mark(1);
}
reader.reset();
System.out.println("我才是完整的一行:" + line);
}
reader.close();
}
原因就是读的line已经是最后一行了,下行已经是null了,对他进行mark,就会有问题了
现在暂时的解决办法是把reader.reset();用try catch包起来,遇到异常了不管,罪恶啊,罪恶
变成:
public static void markLine() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(new File(
"in.txt")));
for (String line = reader.readLine(); line != null && !line.equals(""); line = reader
.readLine()) {
reader.mark(1);
for (int ch = reader.read(); ch == (int) ' ' || ch == (int) '\t'
|| ch == (int) '='; ch = reader.read()) {
reader.reset();
String newLine = reader.readLine();
if (newLine != null)
line += newLine;
reader.mark(1);
}
try {
reader.reset();
} catch (IOException e) {
// IT'S OK
}
System.out.println("我才是完整的一行:" + line);
}
reader.close();
}
哪位高人能指点下我啊,多谢 :arrow:
或者把ch声明提前,在最后一个reset的时候判断ch是否读出了值