134

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()?

Community
  • 1
  • 1
brian
  • 6,802
  • 29
  • 83
  • 124
  • 2
    did you even *try* to search to an existing question that answered your question? – Bohemian Jan 04 '12 at 02:24
  • 5
    Depends; in the central or eastern regions, use Javanese; in the rest, use Indonesian. Most Javanese speakers (except outliers) also speak Indonesian though. Wait, what? – Dave Newton Jan 04 '12 at 02:25

3 Answers3

238

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

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • This answer is a now outdated; the File API has been replaced with the new API, where it'd be: `Paths path = Paths.get("/path/to/file"); long size = Files.size(path);` See [API docs](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#size(java.nio.file.Path)). – rzwitserloot Oct 21 '20 at 16:03
  • @rzwitserloot thank you! I updated my answer with your suggestion. – Óscar López Oct 21 '20 at 16:09
  • oh, fantastic. I never know how to deal with great answers which have been overtaken by time. But, hey, if the original author is around to update things, so much the better. Gracias! – rzwitserloot Oct 21 '20 at 17:33
44

Try this:

long length = f.length();
Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Nat
  • 3,587
  • 20
  • 22
17

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.

Mitch
  • 399
  • 1
  • 5
  • 2
    **I found this code in this site only: and is very useful** public static long folderSize(File directory) { long length = 0; for (File file : directory.listFiles()) { if (file.isFile()) length += file.length(); else length += folderSize(file); } return length; } – abhilash_goyal Mar 31 '14 at 18:07