The getFreeSpaceKb(String path)
method in the FileSystemUtils
class can help you to calculate the free space of a drive or volume in kilobytes.
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.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 = "F:/Temp";
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 F:/Temp = 323413052 KB
Size of F:/Temp = 315833 MB
Size of F:/Temp = 308 GB
Maven Dependencies
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.16.1</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024