我尝试检查是否已到达文件的末尾,但是使用空字符串的条件不起作用
public void readEquation(String fileName) {
File aFile = new File(fileName);
String line = null;
int cnt = 0;
try {
FileReader reader = new FileReader(aFile);
BufferedReader bufferedReader = new BufferedReader(reader);
while ((line = bufferedReader.readLine()) != null) {
//but line gets null
intoMap(line, cnt);
cnt++;
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
答案 0 :(得分:1)
你错误地读了两行而不是一次。循环的条件自己读取一行,然后在循环内读取另一行。我建议这个改变:
public void readEquation(String fileName) {
File aFile = new File(fileName);
String line = null;
int cnt = 0;
try {
FileReader reader = new FileReader(aFile);
BufferedReader bufferedReader = new BufferedReader(reader);
line = bufferedReader.readLine();
while (line != null) {
intoMap(line, cnt);
cnt++;
line = bufferedReader.readLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
答案 1 :(得分:0)
你正在连续阅读两行:一行处于循环状态,另一行处于循环体内。您在条件中读取的那个被忽略并且从未使用过。什么都没有检查第二行的值。
通常人们会这样写这个循环:
while ((line = bufferedReader.readLine()) != null) {
intoMap(line, cnt);
cnt++;
}
这样你就可以在使用它之前检查它。
答案 2 :(得分:0)
while ((bufferedReader.readLine()) != null) {
line = bufferedReader.readLine(); //but line gets null
你在这里读了两行。
要避免使用tmp String之类的
String line=null;
while ((line=bufferedReader.readLine()) != null) {
//now line stores line from file or null if file doesn't have new line
编辑 - 示例
我刚刚测试了这段代码
BufferedReader bufferedReader=null;
try {
String line = null;
bufferedReader = new BufferedReader(new FileReader("d:\\ranks.txt"));
while ((line=bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
并且有效。
答案 3 :(得分:0)
您的代码存在的问题是,当您在while条件下执行bufferedReader.readLine()时,您已经在读取该行了。
你应该这样做:
public void readEquation(String fileName) {
File aFile = new File(fileName);
String line = null;
int cnt = 0;
try {
FileReader reader = new FileReader(aFile);
BufferedReader bufferedReader = new BufferedReader(reader);
while ((line = bufferedReader.readLine()) != null) { // only reads once
intoMap(line, cnt);
cnt++;
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
答案 4 :(得分:0)
这对你有用。
while ((line = bufferedReader.readLine()) != null) {
intoMap(line, cnt);
cnt++;
}