Get available space

Java FileStore class allows you to access information about a systems files store such as available space, total space and used space.

Setup

private static final String SOURCE = "com/levelup/java/io/get-free-space.txt";

Path source;

@Before
public void setUp () throws IOException, URISyntaxException {

    source = Paths.get(this.getClass().getClassLoader().getResource(SOURCE).toURI());    
}

Straight up Java

File.getFreeSpace

@Test
public void get_available_space () {
    
    File file = source.toFile();
    
    long freeSpace = file.getFreeSpace();
    
    assertTrue(freeSpace > 0);
}

Java 7 File I/O

@Test
public void get_available_space_nio () throws IOException {

    FileStore store = Files.getFileStore(source);

    long availableSpace = store.getUsableSpace() / 1024;
    
    assertTrue(availableSpace > 0);
}

Apache Commons

@Test
public void get_available_space_apache_commons () throws IOException {
    
    long freeSpace = FileSystemUtils.freeSpaceKb("/");
    
    assertTrue(freeSpace > 0);
}