Java Files.getFileStore
Find the storage volume that contains an existing entry.
A simple example
Files.getFileStore
- Start with Example volume with 10 units total and 4 available
- Do this Compare a 3-unit request with available space
- Result It fits
Syntax
public static FileStore getFileStore(Path path) throws IOException
JDK 21 declarations (1)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaInspect storage for a recording session
A music teacher is choosing where to save a recording. The recording app must query the volume containing the actual destination folder rather than assuming the system drive has the same capacity.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
var store = Files.getFileStore(desk);
System.out.println(store.getTotalSpace() > 0);
System.out.println(store.getUsableSpace() >= 0);
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true true
The example prints stable checks while obtaining the real capacity figures for this destination.
Check support before displaying permission controls
A file manager offers a POSIX permissions editor only on compatible storage. Ask the target folder's store about its attribute views and print the editor the user can open on the test machine's POSIX volume.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
var store = Files.getFileStore(desk);
System.out.println(store.supportsFileAttributeView("basic"));
String mode = store.supportsFileAttributeView("posix") ? "POSIX" : "basic only";
System.out.println(mode);
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true POSIX
The editor can branch on the actual store capability instead of inferring it from the operating system name.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. On a drive with room to spare, compare its available byte count with the size of one extra copy. Can this copy fit?
What to watch for
Names and capacities vary between devices. Available space can change before a write completes.