我正在编写一个程序,需要打开一个文件,添加它,然后关闭它。出于某种原因,当我尝试这样做时,我得到一个nullPointerException。 以下是我在主要课程中的内容:
public static filer f = new filer();
然后:
f.addStuff("hi");
f.closeFile();
现在这里是我在文件类中的内容,我认为现在的问题是: 公共类文件管理器{
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();
}
其他课程都有效,我有所有适当的进口和东西 哦,当然这是控制台出来的东西:
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)
答案 0 :(得分:2)
您收到NullPointerException
因为当您调用addStuff
方法时,f
尚未初始化,因此null
。在对null
对象的引用上调用方法将导致NullPointerException
。
问题在于openFile
中的以下行。您正在创建一个名为f
的新局部变量,该变量隐藏了在类级别声明的名为f
的字段:
Formatter f = new Formatter(file);
更改以上行,以便类级别字段f
是在openFile
中初始化的字段:
f = new Formatter(file);