2014-01-28 69 views
0

我試圖刪除名稱爲TRTHIndicative_的文件夾中的特定文件。文件不在刪除

但文件不會被刪除,現在用下面的代碼

testMethod(inputDir); 
testMethod(outputFile); 


private static void testMethod(String dirName){ 
    File directory = new File(dirName); 

    // Get all files in directory 
    File[] files = directory.listFiles(); 
    for (File file : files) { 

     if (file.getName().startsWith("Indicative_")) { 
      // Delete each file 
      if(file.exists()){ 
       System.out.println("File is there!"); 
      } 
      if (file.delete()) { 
       // Failed to delete file 
       System.out.println("Failed to delete " + file); 
      } else { 
       System.out.println("Deleted file succsfully"); 
      } 
     } 

    } 

請讓我知道如果有什麼錯。

+0

您在if-else語句中的順序錯誤。如果file.delete()則該文件被刪除。 –

+0

[刪除使用刪除()的文件的可能的重複 - Java](http://stackoverflow.com/questions/3809418/deleting-a-file-using-delete-java) – Lijo

+0

重複的問題已被問到 – Lijo

回答

1

你有你的ifelse困惑 - File#delete()返回true如果文件是成功刪除。所以,條件應該顛倒:

if (file.delete()) { 
    System.out.println("Deleted file succesfully"); 
} else { 
    // Failed to delete file 
    System.out.println("Failed to delete " + file); 
} 
+0

謝謝........! – user3243364

1

Mureinik是對的。 我只是試過你的和平代碼。它工作正常。只是做了如下改變:

public class Main { 

public static void main(String[] args) { 
    File directory = new File("C:/temp"); 
    File[] files = directory.listFiles(); 
    for (File file : files) { 

     if (file.getName().toLowerCase().startsWith("blub")) { 
      // Delete each file 
      if (file.exists()) { 
       System.out.println("File is there!"); 
      } 
      if (file.delete()) { 
       System.out.println("Deleted file succsfully"); 
      } else { 
       // Failed to delete file 
       System.out.println("Failed to delete " + file); 
      } 
     } 
    } 
} 

}

注意toLowerCase()我補充道。它會使您的代碼段更易於使用。

+0

感謝您的迴應!我收到此錯誤:無法刪除C:\ Data_in \ TRTHIndicative_20.txt – user3243364