11

Is there any implementation difference between file.length() and Files.size() in Java? Java 7 introduced Files.size() method.

3 Answers 3

20

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).

Sign up to request clarification or add additional context in comments.

Comments

6

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.

1 Comment

According to the docs Files.size(Path path) does return the "actual file size": Returns the size of a file (in bytes). The size may differ from the actual size on the file system due to compression, support for sparse files, or other reasons.
3

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 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.