Implementing files.size () in Java 7

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

+5
source share
3 answers

A class java.nio.file.Filesin JDK 7 is a class that provides static methods that work with files.

The method Files.size(String path)returns the file size based on java.nio.file.spi.FileSystemProvider. This has nothing to do with File.length(), as it returns you the actual size of the file, which is actually "connected" to.

+5
source

The main difference is that it Files.size()can handle things that are not “regular files” (as defined ). Files.isRegularFile()

, , FileSystemProviders , ZIP , , FTP/SFTP,...

File.length() . "" (.. , ).

+17

, Files.size() IOException, - , File.length() 0. Files.size(), :

  • File.length(), 0.
  • , File.length(). , IOException Files.size() , .

In addition, as described in this answer , it Files.size()can work with any file system provider (for example, for ZIP or FTP file systems), and it File.length()works only with the "regular" file system open by your operating system.

Conclusion In general, prefer methods from a newer class Filesover an old class File.

+1
source

All Articles