The getFreeSpaceKb(String path)
method in the FileSystemUtils
class can help you to calculate the free space of a drive or volume in kilo bytes.
Beside using commons-io
solution, you can use the File.getFreeSpace()
method call provided in the Java 1.6 API. You can find an example of it in the following link: How do I get total space and free space of my disk?.
package org.kodejava.example.commons.io;
import org.apache.commons.io.FileSystemUtils;
import org.apache.commons.io.FileUtils;
import java.io.IOException;
public class DiskFreeSpace {
public static void main(String[] args) {
try {
String path = "/Users/wayan";
long freeSpaceKB = FileSystemUtils.freeSpaceKb(path);
long freeSpaceMB = freeSpaceKB / FileUtils.ONE_KB;
long freeSpaceGB = freeSpaceKB / FileUtils.ONE_MB;
System.out.println("Size of " + path + " = " + freeSpaceKB + " KB");
System.out.println("Size of " + path + " = " + freeSpaceMB + " MB");
System.out.println("Size of " + path + " = " + freeSpaceGB + " GB");
} catch (IOException e) {
e.printStackTrace();
}
}
}
An example result of the code above is:
Size of /Users/wayan = 70583428 KB
Size of /Users/wayan = 68929 MB
Size of /Users/wayan = 67 GB
Maven Dependencies
<!-- http://repo1.maven.org/maven2/commons-io/commons-io/2.6/commons-io-2.6.jar -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020