I am looking to get accurate (i.e. the real size on disk and not the normal size that includes all the 0's) measurements of sparse files in Java.
In C++ on Windows one would use GetCompressedFileSize
. I have yet to come across how one would go about doing that in Java?
If there isn't a direct equivalent, how would I go about measuring the data within a sparse file, as opposed to the size including all of the zeros?
For clarification, I am look for this to run the spare file measurements on both on Linux OS as well as Windows, however I don't mind coding two separate applications!
If you are doing it on Windows alone, you can write it with Java Native Interface
class NativeInterface{
public static native long GetCompressedFileSize(String filename);
}
and in C/C++ file:
extern "C"
JNIEXPORT jlong JNICALL Java_NativeInterface_GetCompressedFileSize
(JNIEnv *env, jobject obj, jstring javaString)
{
const char *nativeString = env->GetStringUTFChars(javaString, 0);
char buffer[512];
strcpy(buffer, nativeString);
env->ReleaseStringUTFChars(javaString, nativeString);
return (jlong) GetCompressedFileSize(buffer, NULL);
}
If you want a pure Java solution you can try jnr-posix. Here's an example implementation
import jnr.posix.*;
final POSIX p = POSIXFactory.getPOSIX();
final int S_BLKSIZE = 512; // from sys/stat.h
final FileStat stat = p.stat("/path/to/file");
final long bytes = stat.blocks() * S_BLKSIZE;
However currently the function won't work for Windows. Until that's fixed you have to use platform-specific code like below
For more information you can read the below questions
- How do I query "Size on disk" file information?
- Get size of file on disk
Since an answer was given for windows. i will try to supply for Linux.
I am not sure, but i think it will do the trick (C++):
#include <linux/fs.h>
ioctl(file, BLKGETSIZE64, &file_size_in_bytes);
This can be loaded in the same way that was described in the @Aniket answer (JNI)