[英]RandomAccessFile Vs NIO Channel
我試圖了解以下行為。 我的舊代碼,
String path = "C:/temp/sample.txt";
String mode= "rw";
FileChannel channel = new RandomAccessFile(path, mode).getChannel();
// some code to write to this file
// finally delete
File file = new File(path);
boolean isDeleted = file.delete();
System.out.println("Is Deleted - " + isDeleted);
O / P - 被刪除 - 錯誤
只有我做了“channel.close();” 在我刪除文件之前。 它是否刪除該文件並返回true。
更換的代碼更新,
String path = "C:/temp/sample.txt";
FileChannel fChannel = FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
// some code to write to this file
// finally delete
File file = new File(path);
boolean isDeleted = file.delete();
System.out.println("Is Deleted - " + isDeleted);
O / P - 被刪除 - 是的
但是在應用程序退出之前,這不會刪除該文件。 如果我使用“fChannel.close()”,它會立即刪除它。
幾個問題,
我不知道我是否遇到了錯誤或遺漏了什么。 任何指針都可以提供幫助。
謝謝
從RandomAccessFile.getChannel()
的規范:
返回通道的位置始終等於getFilePointer方法返回的此對象的文件指針偏移量。 無論是顯式地還是通過讀取或寫入字節,更改此對象的文件指針偏移量都將改變通道的位置,反之亦然。 通過此對象更改文件的長度將更改通過文件通道看到的長度,反之亦然。
換句話說,返回的通道和RandomAccessFile
保持雙向關系,並且兩者都是打開或關閉的。 所以在這方面,它不是FileChannel
而是RandomAccessFile
,它在通道打開時仍然打開,使File
鎖定。
當你在這樣的FileChannel
上調用close
時,它也將關閉相關的RandomAccessFile
,讓JRE中沒有任何內容阻止delete
操作。
相反,當通過FileChannel.open
創建FileChannel
,它沒有關聯的FileInputStream
, FileOutputStream
和RandomAccessFile
,也不會阻止File.delete
操作。
因此,當JVM / JRE中沒有任何內容阻止delete
操作時,它將展示底層操作系統的行為,例如在Microsoft Windows
:
DeleteFile函數
刪除現有文件。
...
DeleteFile函數在關閉時標記要刪除的文件。 因此,在關閉文件的最后一個句柄之前不會發生文件刪除。 使用ERROR_ACCESS_DENIED后續調用CreateFile以打開文件失敗。
這正是觀察到的行為。 您不需要退出JVM,關閉FileChannel
就足以完成刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.