2014-11-06 126 views
1

我有一個應用程序可以創建一個.txt文件。我想覆蓋它。這是我的功能:如何覆蓋現有的.txt文件

try{ 
    String test = "Test string !"; 
    File file = new File("src\\homeautomation\\data\\RoomData.txt"); 

    // if file doesnt exists, then create it 
    if (!file.exists()) { 
     file.createNewFile(); 
    }else{ 

    } 

    FileWriter fw = new FileWriter(file.getAbsoluteFile()); 
    BufferedWriter bw = new BufferedWriter(fw); 
    bw.write(test); 
    bw.close(); 

    System.out.println("Done"); 
}catch(IOException e){ 
    e.printStackTrace(); 
} 

我應該在else子句中放置什麼,如果文件存在,那麼它可以被覆蓋?

+1

[改寫txt文件在Java]的可能的複製(http://stackoverflow.com/questions/13729625/overwrite-txt-file-in-java) – Galabyca 2016-03-08 15:25:09

回答

5

你不需要在else子句中做任何特別的事情。實際上,你可以打開一個Writer文件有兩種不同的模式:

  • 默認模式,這將覆蓋整個文件
  • 追加模式(由一個布爾值設置爲true在構造函數中指定)的新數據追加到現有的一個
+1

「你不需要在else子句中做任何特別的事情......」其實你的意思是,他也不應該有if子句。只是試圖想出自己的一些聰明的評論:) – 2014-11-06 17:19:11

+0

我認爲'createNewFile'會創建文件的所有不存在的父目錄,但看了文檔後,它不會('File.mkdirs ()')。所以是的,if語句在這裏是不必要的 – Dici 2014-11-06 17:32:31

2

只需在你的else塊中調用file.delete()即可。這應該刪除文件,如果這是你想要的。

+1

他不想刪除文件,他想覆蓋它。他在談論刪除,因爲他不知道'Writer'是如何工作的,並且認爲他需要刪除文件以覆蓋它。 – Dici 2014-11-06 17:15:00

+0

他可以刪除它,然後按照不存在的方式執行相同的操作。這就是爲什麼我說「如果這就是你想要的」,我不太確定他想要什麼。 – 2014-11-06 17:15:53

+0

那麼爲什麼要刪除它,因爲他會在沒有這樣做的情況下獲得相同的結果? – Dici 2014-11-06 17:16:56

0
FileWriter(String fileName, boolean append) 

構造一個FileWriter對象,給定一個帶有布爾值的文件名,該布爾值指示是否附加寫入的數據。

下面的一行代碼將幫助我們使文件變空。

FileUtils.write(new File("/your/file/path"), "") 

下面的代碼將幫助我們刪除文件。

try{ 

      File file = new File("src\\homeautomation\\data\\RoomData.txt"); 

      if(file.delete()){ 
       System.out.println(file.getName() + " is deleted!"); 
      }else{ 
       System.out.println("Delete operation is failed."); 
      } 

     }catch(Exception e){ 

      e.printStackTrace(); 

     } 
0

你不需要做任何事情,默認行爲是覆蓋。

不知道爲什麼,我downvoted,嚴重...此代碼將始終覆蓋文件

try{ 
     String test = "Test string !"; 
     File file = new File("output.txt"); 

     FileWriter fw = new FileWriter(file.getAbsoluteFile()); 
     BufferedWriter bw = new BufferedWriter(fw); 
     bw.write(test); 
     bw.close(); 

     System.out.println("Done"); 
    }catch(IOException e){ 
     e.printStackTrace(); 
    } 
+0

是的,他是對的。它會覆蓋。 – mirzak 2014-11-06 17:26:41