2013-12-13 31 views
-2

工作這是我寫刪除一個文件,如果它已經存在File.exists沒有在Java

public void createFile(Map<String, String> map, String name) 
{ 
    try 
    { 
     System.out.println("Creating new File..."); 
     File file = new File("./Analysis/files/master.csv"); 
     if (file.exists()) 
     { 
      System.out.println("File Deleted...."+file.delete()); 
     } 
     System.out.println("New File Created "+file.createNewFile()); 
     FileWriter fw = new FileWriter(file, true); 
     for (Map.Entry<String, String> entry : map.entrySet()) 
     { 
      fw.write(entry.getKey()); 
      fw.write(","); 
      fw.write(entry.getValue()); 
      fw.write("\n"); 
      fw.flush(); 
     } 
     fw.close(); 
    }catch(IOException e) 
    { 
     throw new BuildException(e.getMessage()); 
    } 
} 

這file.exists正顯示出它已存在於該路徑,以便文件錯誤代碼的不刪除該文件並將內容附加到該文件。任何想法?

+1

該文件,如果不再存在已被刪除,你必須刷新更新內容的文件夾。 – 2013-12-13 15:08:56

+3

您至少需要學習縮進代碼。 – kviiri

+0

@nikpon你的觀點是什麼? – Freak

回答

0

您可能需要提供文件的完整路徑。

使用file.getAbsoluteFile().exists()

檢查類似的帖子here

+0

爲什麼需要完整路徑?使用相對路徑沒有任何問題。用戶只需確保它與他們認爲的相關。 – MxyL

+0

有一些與Windows 7的問題..看到類似的答案。 .. http://stackoverflow.com/questions/919918/file-exists-returns-false-when-file-exists – stinepike

+0

感謝您指出。我在Win7上,沒有任何這些問題(在我創建的測試文件中,沒有其他進程使用它),所以這可能是錯誤不會發生在我身上的原因。 – MxyL

3

如果你改變嘗試

FileWriter fw = new FileWriter(file, true); 

FileWriter fw = new FileWriter(file, false); 

它不會追加文本,但貼上新

編輯:

public void createFile(Map<String, String> map, String name) 
{ 
    try 
    { 

    File file = new File("./Analysis/files/master.csv"); 
    FileWriter fw = new FileWriter(file, false); 
    for (Map.Entry<String, String> entry : map.entrySet()) 
    { 
     fw.write(entry.getKey()); 
     fw.write(","); 
     fw.write(entry.getValue()); 
     fw.write("\n"); 
     fw.flush(); 
    } 
    fw.close(); 
}catch(IOException e) 
{ 
    throw new BuildException(e.getMessage()); 
} 
} 
+0

+1。這個。 OP甚至不會檢查「是否存在」。這照顧它。如果該文件不存在或將被覆蓋,該文件將被創建。我不確定爲什麼OP首先使用了「true」。 – MadConan

+0

http://windows.microsoft.com/en-us/windows/show-hide-file-name-extensions#show-hide-file-name-extensions=windows-7 –

+0

這是我遵循的鏈接和它的工作現在罰款 –

0

的FileWriter將要使用規範的文件形式來創建文件。因此,對照相同的表格進行檢查,看看是否符合您的期望。

更改前兩行的代碼這樣:

File file = new File("./Analysis/files/master.csv").getCanonicalFile(); 
System.out.println("Creating new File "+ file.getAbsolutePath());