How to find how much disk space is left using Java?

JavaDiskspace

Java Problem Overview


How to find how much disk space is left using Java?

Java Solutions


Solution 1 - Java

Have a look at the File class http://java.sun.com/javase/6/docs/api/java/io/File.html#getTotalSpace()">documentation</a>;. This is one of the new features in 1.6.

These new methods also include:

  • public long getTotalSpace()
  • public long getFreeSpace()
  • public long getUsableSpace()


If you're still using 1.5 then you can use the http://commons.apache.org/io/description.html">Apache Commons IO library and its http://commons.apache.org/proper/commons-configuration/apidocs/org/apache/commons/configuration/FileSystem.html">FileSystem class

Solution 2 - Java

Java 1.7 has a slightly different API, free space can be queried through the FileStore class through the getTotalSpace(), getUnallocatedSpace() and getUsableSpace() methods.

NumberFormat nf = NumberFormat.getNumberInstance();
for (Path root : FileSystems.getDefault().getRootDirectories()) {
    
    System.out.print(root + ": ");
    try {
        FileStore store = Files.getFileStore(root);
        System.out.println("available=" + nf.format(store.getUsableSpace())
                            + ", total=" + nf.format(store.getTotalSpace()));
    } catch (IOException e) {
        System.out.println("error querying space: " + e.toString());
    }
}

The advantage of this API is that you get meaningful exceptions back when querying disk space fails.

Solution 3 - Java

Use CommonsIO and FilesystemUtils:

https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileSystemUtils.html#freeSpaceKb()

e.g.

FileSystemUtils.freeSpaceKb("/"); 

or built into the JDK:

http://java.sun.com/javase/6/docs/api/java/io/File.html#getFreeSpace()

new File("/").getFreeSpace();

Solution 4 - Java

in checking the diskspace using java you have the following method in java.io File class

  • getTotalSpace()
  • getFreeSpace()

which will definitely help you in getting the required information. For example you can refer to http://javatutorialhq.com/java/example-source-code/io/file/check-disk-space-java/ which gives a concrete example in using these methods.

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
QuestionRoman KaganView Question on Stackoverflow
Solution 1 - JavaKrednsView Answer on Stackoverflow
Solution 2 - JavaprungeView Answer on Stackoverflow
Solution 3 - JavaJonView Answer on Stackoverflow
Solution 4 - Javauser2237049View Answer on Stackoverflow