Java 文件格式化正确顺序

Java file Formatting proper order

我正在编写一个程序,需要打开一个文件,向其中添加内容,然后关闭它。出于某种原因,当我尝试这样做时,我得到了一个 nullPointerException。 这是我的主要内容 class:

public static filer f = new filer();

然后:

f.addStuff("hi");
f.closeFile();

现在这是我在文件 class 中的内容,这就是我认为现在的问题所在: public class 文件管理器 {

private static Formatter f;//to add to file
private static Scanner s; //to read file
public static File file;
private static boolean ftf = false;

public static void openFile() {
    try{ //exception handling
         file = new File("jibberish.txt");
          //shows if file created
         System.out.println("File created: "+ ftf);
         // deletes file from the system
         file.delete();
         // delete() is invoked
         System.out.println("delete() method is invoked");
         // tries to create new file in the system
         ftf = file.createNewFile();
         // print
         System.out.println("File created: "+ ftf);

        Formatter f = new Formatter(file);
        Scanner s = new Scanner(file);
        FileReader r = new FileReader(file);
        /*
        f = new Formatter("jibberish.txt");  //will automatically create jibberish.txt if no exist
        s = new Scanner("jibberish.txt");
        */  //don't us these because scanner will take type string, easier to clear all other way
    }
    catch(IOException ioe){ 
        System.out.println("Trouble reading from the file: " + ioe.getMessage());
    }
}

public static void addStuff(String toAdd){
    f.format("%s ", toAdd);
    System.out.printf("%s added", toAdd);
}

public static void closeFile(){ //need to do this to avoid errors
    f.close();
    s.close();
}

class 的其余部分有效,我有所有正确的导入和东西 哦,当然这是控制台输出的内容:

File created: false
delete() method is invoked
File created: true
Exception in thread "main" java.lang.NullPointerException
at filer.addStuff(filer.java:48)
at transMain.main(transMain.java:40)

你得到一个 NullPointerException 因为当你调用 addStuff 方法时,f 还没有被初始化,因此是 null。在对 null 对象的引用上调用方法将导致 NullPointerException

问题出在 openFile 中的以下行。您正在创建一个名为 f 的新局部变量,它隐藏了在 class 级别声明的名为 f 的字段:

Formatter f = new Formatter(file);

按如下方式更改上面的行,使 class 级别字段 f 是在 openFile 中初始化的那个:

f = new Formatter(file);