使用FileReader测试文件是否为空
我正在尝试向while循环中的代码块添加一个else if
,在该循环下面测试LandingsData.txt
文件是否为空。如果为空,则打印"Starting with an empty system"
FileReader fr = null;
try {
fr = new FileReader("LandingsData.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
Scanner myFile = new Scanner(fr);
String line;
myFile.useDelimiter(",|\\n");
while (myFile.hasNext()) {
line = myFile.next();
if (line.equals("sl")) {
StrongLanding sl = new StrongLanding();
sl.setLandingId(Integer.parseInt(myFile.next()));
sl.setLandingDesc(myFile.next());
sl.setNumLandings(Integer.parseInt(myFile.next()));
sl.setCost(Double.parseDouble(myFile.next()));
landings.add(sl);
} else if (line.equals("ul")) {
UltimateLanding ul = new UltimateLanding();
ul.setLandingId(Integer.parseInt(myFile.next()));
ul.setLandingDesc(myFile.next());
ul.setNumLandings(Integer.parseInt(myFile.next()));
ul.setCost(Double.parseDouble(myFile.next()));
landings.add(ul);
} else if (fr.length() == 0) {
System.out.println("Starting with an empty system");
}
}
我用fr.length()
或fr.count()
尝试了几种不同的方法,但我似乎收到了错误The method length() is undefined for the type FileReader
我还尝试了while循环之外的几个不同的地方,因为我认为这可能是问题所在,但没有运气
短暂性脑缺血发作
# 1 楼答案
在读取文件之前调用
hasNext()
一次,查看文件是否为空# 2 楼答案
您可以使用以下代码检查文件是否为空:
使用
File
类而不是FileReader
或者,如果需要使用
FileReader
,可以这样做:在开始while循环之前进行检查,将第一行与两个字符串进行比较,然后检查文件是否为空