Files.size() implementation in Java 7
Is there any implementation difference between file.length()
and Files.size()
in Java? Java 7 introduced 开发者_如何学PythonFiles.size()
method.
The main difference is that Files.size()
can handle things that are not "regular files" (as defined by Files.isRegularFile()
).
This means that depending on which FileSystemProviders
you have available, it could be able to get the size of a file in a ZIP file, it could be able to handle files accessed via FTP/SFTP, ...
Plain old File.length()
can not do any of that. It only handles "real" files (i.e. those that the underlying OS handles as files as well).
The java.nio.file.Files
class in JDK 7 is a class that provides static methods that operates on files.
The Files.size(String path)
method returns the file size based from the java.nio.file.spi.FileSystemProvider
. It's not nothing to do with File.length()
as this returns you the actual file size that actually has "connected" to.
An important difference is that Files.size()
throws an IOException if something goes wrong, while File.length()
simply returns 0. I would therefore recommend using Files.size()
because:
- It's not possible to differentiate between an empty file and an error occurring with
File.length()
because it will return 0 in both cases. - If an error occurs you won't get any information on the cause of the error with
File.length()
. In contrast, the IOException thrown fromFiles.size()
will generally include a message indicating the cause of the failure.
Additionally, as described in this answer, Files.size()
can work with any file system provider (e.g. for ZIP or FTP file systems) while File.length()
only works with the "regular" file system exposed by your operating system.
Conclusion: In general, prefer methods from the newer Files
class over the legacy File
class.
精彩评论