If a file is a sparse file that means its physicalSize / logicalSize should be lover than 1. If you can calculate this values than you can undrestand if this file is sparse file or not.
To do that first you need to get the file is physicalSize. You should use different methods for windows and linux to calculate that value.
There is no direct API for that so you need to use ProcessBuilder for this:
for linux:
Path path = Paths.get(filePath);
File file = path.toFile();
Long physicalSize = 0;
// create and run the process
Process process = new ProcessBuilder("du", "--block-size=1",file.getAbsolutePath()).redirectErrorStream(true).start();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line = reader.readLine();
if (line != null) {
String[] parts = line.split("\\s+");
// take the value from return string should be something like: 9379 filename
physicalSize = Long.parseLong(parts[0]);
}
}
process.waitFor();
After you capture the physical Size you need to capture the logical Size for the file, simply you can do it like this:
Path path = Paths.get(filePath);
long logicalSize = Files.size(path);
And finally you can use these 2 values to determine whether its a sparse file or not:
double sparseness = (double) physicalSize / logicalSize;
if (sparseness < 1) {
System.out.println("a sparse file");
} else {
System.out.println("not a sparse file");
}