How to get file size in Java
Use the length()
method in the File
class. From the javadocs:
Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.
UPDATED Nowadays we should use the Files.size()
method:
Path path = Paths.get("/path/to/file");
long size = Files.size(path);
For the second part of the question, straight from File
's javadocs:
getUsableSpace()
Returns the number of bytes available to this virtual machine on the partition named by this abstract pathnamegetTotalSpace()
Returns the size of the partition named by this abstract pathnamegetFreeSpace()
Returns the number of unallocated bytes in the partition named by this abstract path name
Try this:
long length = f.length();