How to get file size in Java

Java

Java Problem Overview


> Possible Duplicate:
> Size of folder or file

I used this code to instantiate a File object:

File f = new File(path);

How do I get the size of this file?

What is the difference between getUsableSpace(), getTotalSpace(), and getFreeSpace()?

Java Solutions


Solution 1 - 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 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

Solution 2 - Java

Try this:

long length = f.length();

Solution 3 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbrianView Question on Stackoverflow
Solution 1 - JavaÓscar LópezView Answer on Stackoverflow
Solution 2 - JavaNatView Answer on Stackoverflow
Solution 3 - JavaMitchView Answer on Stackoverflow