【发布时间】:2013-04-16 14:13:19
【问题描述】:
所以我想要做的是读取.txt 文件并使用 Eclipse 在其上添加一些记录。我将我命名为“fileName”的资源设置为私有,当我尝试在 main 方法中调用它时,出现了一些错误。这是我的代码:
public class FileController {
private String fileName;
public FileController() {
}
public FileController(String fileName) {
fileName = "student.txt";
}
public void readLine() {
try {
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
// read in the file line by line
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
fr.close();
} catch (FileNotFoundException exception) {
System.out.println("The file " + fileName + " was not found.");
} catch (IOException exception) {
System.out.println(exception);
}
}
public void writeLine() {
try {
// create the PrintWriter
FileWriter fw = new FileWriter(fileName, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
// write value out to the file
outFile.println("Coke is nice");
outFile.println("Diet Coke is even better cos won't put on weight =)");
// close the file
outFile.close();
System.out.println("File created: " + fileName);
} catch (IOException exception) {
System.out.println(exception);
}
}
public static void main(String[] args) {
FileController fs = new FileController();
fs.readLine();
fs.writeLine();
}
}
谁能给我一些线索?这些代码不断给我 NullPointerException 错误。我知道是FileController fs = new FileController()那行,但我不知道如何在静态方法中调用实例方法。
【问题讨论】:
-
我怀疑该行导致错误。您仔细查看堆栈跟踪了吗?
-
谢谢大家。我已经修好了
标签: java file-io filereader