所以我想做的是读取 .txt
文件并使用 eclipse 在其上添加一些记录。我将命名为“fileName
”的资源设置为私有(private),当我尝试在主方法中调用它时,出现一些错误。这是我的代码:
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()
那一行,但我不知道如何在静态方法中调用实例方法。
最佳答案
尝试:
public FileController() {
fileName = "student.txt";
}
public FileController(String fileName) {
this.fileName = filename;
}
关于java - 如何在静态方法中调用实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16039444/