簡體   English   中英

無法在 Java 中刪除文件,因為它是在 Java Platform SE 二進制文件中打開的

[英]Can not delete file in java beause it's opened in Java Platform SE binary

我在 Windows 上有三個目錄 A、B 和 C。 我有一個存在於目錄 A 中的文件。我想執行以下任務

  1. 復制到目錄B
  2. 從目錄 A 中刪除它(這是有效的,因為該文件未被任何進程保存)
  3. 復制到目錄C
  4. 從目錄 B 中刪除它(不工作)

步驟 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 步嗎?

為什么不使用像 Apache Commons IO (FileUtils) 這樣的庫?

http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html

File a = new File("A/file.txt");
File b = new File("B/file.txt");
File c = new File("C/file.txt");
FileUtils.copyFile(a, b);
a.delete();
FileUtils.copyFile(b, c);
b.delete();

試試這個:

代碼

       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.");
        }
      }

請確保使用正確的 try 和 catch 子句

這里 ,您可以 此處看到如何使用Java刪除文件。

至於您的錯誤消息,它表示您嘗試在文件仍然加載時刪除它。 您可以嘗試在垃圾收集器執行其任務之前刪除該文件,也可以嘗試在某些對象仍在使用它時刪除該文件。 如果要刪除它,請確保您沒有在代碼中引用該文件。

如果您知道如何打開Windows 任務管理器,然后打開它並單擊“進程”,然后單擊頂部的“描述”一詞,然后滾動並查找“ JAVA ”一詞,然后右鍵單擊它並單擊“結束進程樹”。關閉Windows任務管理器並返回文件資源管理器然后返回Java文件並刪除它或打開它以刪除文件中要刪除的任何內容我希望這有助於解決您的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM