Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Files.size() implementation in Java 7

Tags:

java

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

like image 816
UVM Avatar asked Aug 29 '11 05:08

UVM


3 Answers

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.

like image 181
Buhake Sindi Avatar answered Oct 25 '22 09:10

Buhake Sindi


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

like image 20
Joachim Sauer Avatar answered Oct 25 '22 09:10

Joachim Sauer


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.

like image 23
skyewire Avatar answered Oct 25 '22 07:10

skyewire