File size/length

In this chapter you will learn:

  1. How to get the file size
  2. How to get get free space, total space, usable space

Get the file size

long length() returns the file length. The length is in type long.

import java.io.File;
// ja  v  a  2 s  .  c  o  m
public class Main {

  public static void main(String[] args) {
    File aFile = new File("c:/a.htm");
    System.out.println(aFile.length());

  }
}

The output:

Get free space, total space, usable space

The following three helper methods give us the free space, total space and usable space for a given drive.

  • long getFreeSpace()
    Returns the number of unallocated bytes in the partition named by this abstract path name.
  • long getTotalSpace()
    Returns the size of the partition named by this abstract pathname.
  • long getUsableSpace()
    Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname.
import java.io.File;
/*from j ava  2s . c  om*/
public class Main {

  public static void main(String[] args) {
    File aFile = new File("c:/");
    System.out.println(aFile.getFreeSpace());
    System.out.println(aFile.getTotalSpace());
    System.out.println(aFile.getUsableSpace());
  }
}

The output:

12283260928
79990812672
12283260928

Next chapter...

What you will learn in the next chapter:

  1. How to create a new directory and a directory hierarchy