java - 如何查找 BufferedReader 文件中是否存在一行?
问题描述
我在 Java 中有这个方法,它在另一个方法的 try 块中调用。importFormat 在 try 块中返回具有分配值的类(//做需要的事情)。该方法应该逐行读取文件。如果使用 try 块对方法的方法调用被调用的次数多于文件中的行数,则 importFormat() 应返回 null。
我试图用 if 块检查它,虽然它做的不多并且总是返回 ClassName。似乎该类始终存储文件的第一行。
private ClassName importFormat(BufferedReader br) throws IOException, ParseException {
String out;
Track t = new ClassName();
if((out = br.readLine()) == null) return null;
//do what is needed
}else{
t = null; //here I unsuccessfully tried to force the method to again return null, no luck
System.err.print(out);
throw new ParseException("", 0);
}
return t;
}
我也尝试过 br.ready() 方法,它没有任何区别
编辑:我注意到我错误地复制了代码,对此我很抱歉。这里应该更清楚最小可重现代码:
private ClassName foo(BufferedReader br) throws IOException {
ClassName t = new ClassName();
String out = null;
out = br.readLine();
if(out.equals(null)) return null; //handle the case where there's no more line to read
if(/*!string red from BufferedReader.isEmpty()*/){
//do something
}else{
t = null; //ensure that null would be returned
//do something more unrelated to this question
}
return t;
}
解决方案
我不太明白你的问题,但我认为你不应该这样比较:
if((out = br.readLine()) == null) return null;
要在 java 中比较字符串,让我们使用 str1.equals(str2) 代替。所以我认为你应该尝试:
if(out.equals(br.readLine())) {
//do sth here because "out" exists in BufferReader.
} else {
System.out.println("Continue searching...\n");
}
return t;
推荐阅读
- c# - 如何在并行 ForEach 循环中从数组中选择一个随机元素?
- angular - 角primeng树文件夹上下箭头不起作用
- java - 点燃 cron 中的 ClassNotFoundException
- java - sh startAgent.sh 在 MacOS 中不适用于 jmeter perfmon 插件
- c++ - 如何将 libjingle_peerconnection_so.so 链接到项目并从中调用类?
- python - 如何让 Python 尝试从本地文件夹加载模块?
- javascript - 如何在 Visual Studio 中定义 HTML 文件扩展名?
- android - ConcatAdapter 内部的 Paging3 Library 的 PagingDataAdapter 加载所有页面而不滚动
- python - 如何组合多个条目的两个字典列表
- php - 如何修复在 yii2 中获取未知属性