In Java, we can use Files. size(path) to get the size of a file in bytes.
Java get file size using File classJava File length() method returns the file size in bytes. The return value is unspecified if this file denotes a directory. So before calling this method to get file size in java, make sure file exists and it's not a directory.
length() returns the length of the file defined by this abstract pathname. The return value is unspecified if this pathname defines a directory.
What we need is to open the terminal and type du -sh file name in the prompt. The file size will be listed on the first column. The size will be displayed in Human Readable Format. This means we can see file sizes in Bytes, Kilobytes, Megabytes, Gigabytes, etc.
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 pathname
getTotalSpace()
Returns the size of the partition named by this abstract pathname
getFreeSpace()
Returns the number of unallocated bytes in the partition named by this abstract path name
Try this:
long length = f.length();
Did a quick google. Seems that to find the file size you do this,
long size = f.length();
The differences between the three methods you posted can be found here
getFreeSpace() and getTotalSpace() are pretty self explanatory, getUsableSpace() seems to be the space that the JVM can use, which in most cases will be the same as the amount of free space.
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