读取文件并打印所有字母的字符的程序,在到达最后一行时抛出NullPointerException。在到达最后一行后,逐行读取文件行while循环
import java.io.*;
public class Foo {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader(new File("source.txt"));
BufferedReader read = new BufferedReader(file);
String line = read.readLine();
while (line != null) {
for (int i = 0; i < line.length(); i++) {
line = read.readLine(); // this is where the problem is. When it reaches the last line, line = null and the while loop should terminate!
if (Character.isLetter(line.charAt(i))) {
System.out.print(line.charAt(i));
}
}
}
}
}
你想查看您正在使用的BufferedReader的javadoc。看到这里:http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html 自助是最好的帮助。 另请注意,这是一个重复的:http://stackoverflow.com/questions/16265693/how-to-use-buffered-reader-in-java 这里的答案将是相同的。 – ThePerson 2015-02-24 20:19:28
为什么你会尝试阅读与线条长度一样多的线条?这并没有什么意义 – fge 2015-02-24 20:20:17
While循环仅检查每次迭代**开始**处的条件。它们不会因为在下一次迭代开始时条件将为假而终止中间循环。 – chancea 2015-02-24 20:26:27