2012-04-07 49 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爲空,因爲您沒有初始化它。

相關問題