所以我有一個類,它所做的是讀取文件的內容,然後根據內容做一些事情。讀取.txt文件
package maple;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JOptionPane;
public class SetSettings {
public SetSettings() {
BufferedReader reader;
File f = new File (Shared.saveLocation + "Settings.txt");
String line = "";
if (f.exists()) {
while (line != null) {
try {
//System.out.println("COMES HERE");
reader = new BufferedReader(new FileReader(Shared.saveLocation + "Settings.txt"));
line = reader.readLine();
System.out.println(line);
} catch (IOException e2) {
// TODO Auto-generated catch block
//e2.printStackTrace();
//JOptionPane.showMessageDialog(null, "Error Code: Bx001", "Error", 0);
}
}
}
}
}
爲了測試的目的,我把它打印出.txt的每一行。不是打印出.txt文件中的內容,而是打印出第一行。不管如果在.txt文件中有一行或100行,它只會不斷讀取一行。如何讓它讀取下一個並在沒有更多時停止?
停止創建一個新的緩衝讀者。那就是問題所在。在文件聲明旁邊初始化它。 – 2013-07-11 20:36:11
將while條件替換爲:'(line = reader.readLine())!= null'。 – 2013-07-11 20:46:06