問題描述
我想知道 File.exists()
是如何工作的.我不太了解文件系統(tǒng)的工作原理,所以我應(yīng)該先從那里開始閱讀.
I am wondering how File.exists()
works. I'm not very aware of how filesystems work, so I should maybe start reading there first.
但對于快速的預(yù)信息:
調(diào)用 File.exists()
是否是文件系統(tǒng)的單個操作,如果該路徑和文件名已在某個日志中注冊?還是操作系統(tǒng)獲取目錄的內(nèi)容,然后掃描它以查找匹配項?
Is a call to File.exists()
a single action for the filesystem, if that path and filename are registered in some journal? Or does the OS get the content of the directory and then scan through it for matches?
我認(rèn)為這將取決于文件系統(tǒng),但也許所有文件系統(tǒng)都使用快速方法?
I presume this will be filesystem dependant, but maybe all filesystems use the quick approach?
我不是在談?wù)摼W(wǎng)絡(luò)和磁帶系統(tǒng).讓我們把它保存到 ntfs、extX、zfs、jfs :-)
I'm not talking about network and tape systems. Lets keep it to ntfs, extX, zfs, jfs :-)
推薦答案
如果第一次執(zhí)行此操作完全取決于文件系統(tǒng).這是由操作系統(tǒng)完成的,Java 沒有任何作用.
How this operation if performed the first time is entirely dependant on the filesystem. This is done by the OS and Java doesn't play any part.
就性能而言,在所有情況下都需要讀取磁盤.這通常需要 8-12 毫秒.@Sven 指出一些存儲可能會變慢,但在性能很重要的情況下這種情況相對較少.如果這是一個網(wǎng)絡(luò)文件系統(tǒng),您可能會有額外的延遲(通常相對較小,但取決于您的網(wǎng)絡(luò)延遲).
In terms of performance, a read to a disk is required in all cases. This typically takes 8-12 ms. @Sven points out some storage could slower, but this relatively rare in cases where performance is important. You may have an additional delay if this is a network file system (usually relatively small but it depends on your network latency).
相比之下,操作系統(tǒng)和 Java 所做的一切都非常短.
Everything else the OS and Java does is very short by comparison.
但是,如果您反復(fù)檢查文件是否存在,則可能不需要磁盤訪問,因為可以緩存信息,在這種情況下是操作系統(tǒng)占用的時間和資源.File.exists() 創(chuàng)建的這些對象中最大的一個(您不會認(rèn)為它會創(chuàng)建),但是它會在每次調(diào)用創(chuàng)建大量對象時對文件名進(jìn)行編碼.如果你把 File.exists() 放在一個緊密的循環(huán)中,它每秒會產(chǎn)生 400MB 的垃圾.:(
However, if you check the file exists repeatedly, a Disk access may not be required as the information can cached, in this case the time the OS takes and resources. One of the largest of these the objects File.exists() creates (you wouldn't think it would) however it encodes the file's name on every call creating a lot of objects. If you put File.exists() in a tight loop it can create 400MB of garbage per second. :(
通過跟蹤您對文件系統(tǒng)所做的所有更改,日志文件系統(tǒng)的工作方式有所不同,但它們不會改變您讀取文件系統(tǒng)的方式.
Journaling filesystems work differently by keeping track of all the changes you make to a file system, however they don't change how you read the filesystem.
這篇關(guān)于Java 中的 File.exists 有多貴的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!