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;
//from java 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  a v  a 2 s.c  o  m*/
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
Home » Java Tutorial » File
File
File across Operating System
File properties
File creation
File path
File path compare
File delete
File parent folder
File drive root
File size/length
File new directories
File rename
File modified time
File executable, readable or writable
File location to URI
File copy