2011-03-07 110 views
0

我使用了下列代碼,但我無法刪除該文件。誰能幫忙?無法使用線程刪除文件

public class Delete{ 

    public static void main(final String[] args){ 
     final Thread a = new Thread(); 
     a.start(); 
    } 

    public void run(){ 
     final String fileName = "default\\sample.txt"; 

     // A File object to represent the filename 

     final File f = new File(fileName); 

     // Make sure the file or directory exists and isn't write protected 

     if(!f.exists()){ 
      throw new IllegalArgumentException(

      "Delete: no such file or directory: " + fileName); 
     } 

     if(!f.canWrite()){ 
      throw new IllegalArgumentException("Delete: write protected: " 

      + fileName); 
     } 

     // If it is a directory, make sure it is empty 

     if(f.isDirectory()){ 

      final String[] files = f.list(); 

      if(files.length > 0){ 
       throw new IllegalArgumentException(

       "Delete: directory not empty: " + fileName); 
      } 

     } 

     // Attempt to delete it 

     f.delete(); 

    } 

} 

或者是否有任何其他方式使用線程刪除文件?

+1

縮進,瞭解線程基礎回來。您將可以刪除。 – adarshr 2011-03-07 09:34:14

+0

Cross-posted here:http://www.java-forums.org/threads-synchronization/40088-cant-delete-file.html – 2011-03-07 09:34:55

回答

0

這就是你要找的。

public class Delete extends Thread { 

    public static void main(String[] args) { 

     Thread a = new Delete(); 

     a.start(); 

    } 

    public void run() { 
     // your implementation 
    } 
} 
+0

爲什麼您重新發布格式問題中的代碼?這有什麼幫助?或者我錯過了什麼? – 2011-03-07 09:39:45

+0

嗯,你是對的。除了'extends Thread'部分外,沒有什麼不同了! – adarshr 2011-03-07 09:42:09

+0

謝謝它現在的作品!我需要學習基礎知識:( – Princeyesuraj 2011-03-07 09:43:36

-1

你必須與啓動線程:

Thread a = new Thread(new Delete()); 
a.start(); 

更新:

Delete類還需要實現Runnable

+1

這隻有在'Delete'實現'Runnable'時纔會起作用 – 2011-03-07 09:37:50

+0

啊,錯過了。它確實有'run()'。 – 2011-03-07 09:41:17

+0

更新了帖子。 – 2011-03-07 09:42:17

0

方法的run()不叫

import java.io.File; 

public class Delete extends Thread { 

    public static void main(String[] args) { 

     Delete a = new Delete(); 
     a.start(); 
    } 

    public void run() 
    { 
     String fileName = "C:\\temp\\todelete.txt"; 
     File f = new File(fileName); 
     if (!f.exists()) 
      throw new IllegalArgumentException("Delete: no such file or directory: " + fileName); 
     if (!f.canWrite()) 
      throw new IllegalArgumentException("Delete: write protected: " + fileName); 
     if (f.isDirectory()) { 
      String[] files = f.list(); 
      if (files.length > 0) 
       throw new IllegalArgumentException("Delete: directory not empty: " + fileName); 
     } 

     boolean success = f.delete(); 

     if (!success) 
      throw new IllegalArgumentException("Delete: deletion failed"); 

    } 

}