java - 如何在静态方法中调用实例方法

标签 java file-io filereader

所以我想做的是读取 .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/

相关文章:

javascript - 从图像中读取二进制数据并使用 JavaScript 保存

java与来自多个应用程序实例的redis一起工作

java - 如何将默认文件名设置为 Swing JFileChooser?

jquery - 将带有输入[文件]和选定值的 div 移动到另一个 div

go - bufio.Writer写入后,bufio.Reader不会从文件中读取任何内容

javascript - 从服务器的 csv 文件中提取的数据缺少换行符

java - 获取嵌套在另一个 json 对象中的 json 数组

java - 调用 addValueEventListener 时 Firebase 返回错误值

java - 正则表达式提取范围内的数字

java - SuperFloppyFormatter 对于超过 512 MB 的任何内容都会返回 FAT32?