2013-11-02 50 views
0

我正在爲我的學校創建java項目,但現在我卡在這裏。寫入到txt文件java

我想創建一個程序來創建.txt文件,並將我的輸入從鍵盤寫入它。 但在此之前它會檢查文件是否已經存在。因此,程序不會創建具有相同名稱的新文件,但它會將輸入添加到以前插入的數據。

有時候,我每次運行該程序時都會向該.txt文件添加信息。 在這一刻,一切正常,但除了檢查,如果該文件已經存在。我試圖添加exists();但沒有成功。

我是這個所以請給我一個提示並非所有的解決方案:) 在此先感謝!

代碼

private Formatter output; //object 

     public static String user_name() { 
      String user_name=System.getProperty("user.name"); 
       return user_name; 
      }; 


      public void openFile(){ 
       try { 
        output = new Formatter(user_name()+".txt");  //here I tried to add exists() method to check if the file exists already. but it responded //with undefined method error.  
        } 


       catch (SecurityException securityException) 
       { 
        System.err.println("Jums nav atļauja rediģēt šo failu"); 
        System.exit(1); //izejama no programmas 
       } 
       catch (FileNotFoundException fileNotFoundException) 
       { 
        System.err.print("Kļūda atverot failu"); 
        System.exit(1); //izejama no programmas 
       } 
      } 
+1

我不能看到寫在你的代碼文件中的一部分,但檢查一個文件或文件夾是否存在需要使用具有File對象的存在的方法 –

+0

@Richard刺痛究竟如何我可以從Formatter轉換爲文件對象?謝謝 – Edgars

+1

請參閱sumitb的解決方案。如果所有的syatems都注意「/」只是窗口中的文件夾分隔符 –

回答

2

使用File對象完成這個任務。

File f = new File("YourPathHere"); 

一旦你有,你可以使用這個文件對象存在的功能檢查,如果你想將內容添加到現有的文件(技術上稱爲文件存在與否

f.exists() //returns true if mentioned file exists else return false 

之後附加操作),您可以告訴FileWriter對象以附加模式創建文件流。

output = new BufferedWriter(new FileWriter(yourFileName, true)); //second argument true state that file should be opened in append mode 
+0

非常感謝,代碼的最後一行保存了我的一天:) – Edgars