Java文件格式化的正确顺序
我正在编写一个程序,需要打开一个文件,添加到其中,然后关闭它。由于某种原因,当我尝试这样做时,我会得到一个nullPointerException。 以下是我在主课上学到的内容:Java文件格式化的正确顺序,java,file,logic,formatter,Java,File,Logic,Formatter,我正在编写一个程序,需要打开一个文件,添加到其中,然后关闭它。由于某种原因,当我尝试这样做时,我会得到一个nullPointerException。 以下是我在主课上学到的内容: public static filer f = new filer(); 然后: f.addStuff("hi"); f.closeFile(); 下面是我在file类中的内容,我认为现在的问题是: 公共类文件管理器{ private static Formatter f;//to add to file priv
public static filer f = new filer();
然后:
f.addStuff("hi");
f.closeFile();
下面是我在file类中的内容,我认为现在的问题是:
公共类文件管理器{
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)
您会得到一个
NullPointerException
,因为当您调用addStuff
方法时,f
尚未初始化,因此是null
。对null
对象的引用调用方法将导致NullPointerException
问题在于openFile
中的以下行。您正在创建一个名为f
的新局部变量,它隐藏了在类级别声明的名为f
的字段:
Formatter f = new Formatter(file);
按如下所示更改上述行,以便类级别字段f
是在openFile
中初始化的字段:
f = new Formatter(file);
啊,好的,我以为它是用f.openFile()初始化的;?没关系,你是对的。我不知道我刚才在上面的评论中说了什么。非常感谢,现在就可以了!@Bagel别忘了对答案投赞成票,如果你觉得它帮助你解决了你的问题,请接受它。是的,对不起,我不得不在点击检查之前等待