2013-10-12 23 views
4

我在Windows上有三個目錄A,B & C.我有一個存在於目錄A.文件我想執行下列任務無法刪除java中的文件,因爲它在Java平臺SE二進制文件中打開

  1. 將其複製到目錄中乙
  2. 從目錄中的刪除(這工作,因爲該文件沒有舉行任何處理)
  3. 將其複製到目錄ç
  4. 從目錄中乙將其刪除(不工作)

步驟1,2,3做工精細,但它不與步驟4的文件是否存在,並能編寫工作,閱讀,執行。當我打開Windows資源管理器並嘗試手動刪除目錄B中的文件時,它表示該操作無法完成,因爲它在java平臺SE二進制文件中打開。下面是我的代碼複製文件

 FileInputStream in = new FileInputStream(source); 
     FileOutputStream out = new FileOutputStream(dest); 

     byte[] buf = new byte[1024]; 
     int len; 

     while ((len = in.read(buf)) > 0) { 
      out.write(buf, 0, len); 
     } 

     in.close(); 
     out.close(); 

我正在使用Java 6.你知道我可以如何完成第4步?

+2

如果您只是在最後一步刪除它,將它複製到目錄B有什麼用處? –

+0

看看這個:http://stackoverflow.com/questions/991489/i-cant-delete-a-file-in-java – kol

+0

如果A,B和C都在同一個文件系統中,爲什麼不使用重命名而不是其中一個複製步驟? – EJP

回答

0

試試這個:

代碼

 public void foo(){ 
     File afile =new File("A\\Afile.txt"); 
     File bfile =new File("B\\Bfile.txt"); 
     InputStream inStream = new FileInputStream(afile); 
     OutputStream outStream = new FileOutputStream(bfile); 

     byte[] buffer = new byte[1024]; 

     int length; 
     //copy the file content in bytes 
     while ((length = inStream.read(buffer)) > 0){ 

      outStream.write(buffer, 0, length); 

     } 

     inStream.close(); 
     outStream.close(); 

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

請確保您使用正確的嘗試和catch子句

+2

由於它被Java SE二進制進程持有,我仍然無法刪除aFile – Andy

-1

Hereherehere你可以看到如何刪除Java中的文件。

至於關於您的錯誤消息,它表明您嘗試在文件仍然加載時刪除該文件。您可以嘗試在垃圾回收器執行其作業之前刪除該文件,或者嘗試在某些對象仍在使用時刪除文件。確保在刪除代碼時未在代碼中引用該文件。