2013-08-07 124 views
0

我需要從Java程序中刪除文件並編寫了此代碼。它無法刪除文件,我不明白爲什麼。該文件未被使用且未被寫保護。Java文件刪除失敗

public static void delfile(String filetodel) { 
    try { 
     File file = new File("filetodel"); 

     if (file.delete()) { 
      System.out.println(file.getName() + " is deleted!"); 
     } else { 
      System.out.println("Delete operation is failed." + filetodel); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
+4

您可能必須刪除那裏有新文件(「filetodel」)的引號,因爲您不使用參數 – Sw4Tish

+2

有什麼例外? – sanbhat

+0

考慮使用新的NIO.2文件API。 – Puce

回答

1

如果你只是想刪除的文件,有無需加載它。

java.nio.file.Files.deleteIfExists(filetodel);(其中filetodel包含文件路徑)

返回true如果文件被刪除,所以你甚至可以把它放在你的if-子句。

7

我想這個問題是這樣的:

File file = new File(filetodel); 

一切似乎罰款:

File file = new File("filetodel"); 

這應該有可能被(從參數filetodel的方法,通過推斷) ,並在我的機器上工作。

+0

嗨,你假設文件將在目前的工作目錄或正在執行的Java文件的相同文件夾。如果它在系統中的其他地方呢?只是一個想法! –

+1

@ VardhanDG。我只假設OP將正確的路徑傳遞給方法中的文件,用'filetodel'表示。 –

+0

當刪除硬編碼路徑只是我的意見 –

0

嘿夥計你應該使用一個路徑作爲參數刪除 static void delete(路徑路徑) 刪除一個文件。 static boolean deleteIfExists(Path path) 刪除文件(如果存在)。

搜索這裏:http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html

所以你的情況

File file = new File("c://user//filetodel"); 

file.delete(); 

或使用getAbsolutePath(文件名),並用它在文件路徑

0

這是我的代碼來刪除文件。

public class deletef 
    { 
     public static void main(String[] args) 
    { 
    try{ 

     File file = new File("/home/rahul/Downloads/ou.txt"); 

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

    }catch(Exception e){ 

     e.printStackTrace(); 

    } 

    } 
} 

你的代碼也是正確的,但你必須把擴展名也文件

File file = new File("filetodel"); 

這裏附加擴展還包括其他文件明智的您的代碼不會刪除文件