讀取文件並打印所有字母的字符的程序,在到達最後一行時拋出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