Is there any implementation difference between file.length()
and Files.size()
in Java? Java 7 introduced Files.size()
method.
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.
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).
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:
File.length()
because it will return 0 in both cases.File.length()
. In contrast, the IOException thrown from Files.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With