2012-04-07 46 views
0

我有一个将文本写入文件的应用程序。如果文件不存在,则会创建该文件。当文件已经存在时尝试启动程序时发生异常

当我第一次运行应用程序时,它一切正常,文件被创建。但是,以后的每一次都会导致应用程序崩溃。请你帮忙解释一下为什么它不能工作多次。

我的代码如下...

public class Apples { 

    Formatter x; 
    File file = new File("myfile.txt"); 

    public Apples() { 

     if (!file.exists()) { 
      try { 
       x = new Formatter("myfile.txt"); 
      } 
      catch (Exception e) { 
       System.out.println("There was an error creating the file"); 
      } 

      System.out.println("The file was created"); 
     } 
     else { 
      System.out.println("The file already exists"); 
      } 

     x.format("%s", "text"); 
     x.close(); 
    } 

    public static void main(String[] args) throws FileNotFoundException { 
     Apples a = new Apples(); 
    } 

} 
+0

你会得到什么错误? – 2012-04-07 04:15:40

+0

System.out.println(“error”); - 请打印出System.out.println(“error:”+ e.getMessage())的全部细节; – 2012-04-07 04:19:37

回答

4

我怀疑问题就行x.format("%s", "text");一个NullPointerException,因为你如果文件已经存在,并不值分配给x

0

第二次x为空,因为您没有初始化它。

相关问题