Dominic
Dominic

Reputation: 299

Size of file which we get through AssetManager function getAssets in Android

AssetManager mngr = getAssets();
test_file = mngr.open("sample.txt");

above test_file variable is of InputStream type. Any way to calculate the file size of sample.txt from it?

Upvotes: 19

Views: 10804

Answers (3)

Stan Kurdziel
Stan Kurdziel

Reputation: 5724

inputStream.available() might match the file size if the file is very small, but for larger files it isn't expected to match.

For a compressed asset, the only way to get the size reliably is to copy it to the filesystem, ex: context.getCacheDir() then read the length of the file from there. Here's some sample code that does this. It probably then also makes sense to use the file from the cache dir as opposed to the assets after this.

String filename = "sample.txt";
InputStream in = context.getAssets().open(filename);
File outFile = new File(context.getCacheDir(), filename);
OutputStream out = new FileOutputStream(outFile);

try {
    int len;
    byte[] buff = new byte[1024];
    while ((len = in.read(buff)) > 0) {
        out.write(buff, 0, len);
    }
} finally {
    // close in & out
}
long theRealFileSizeInBytes = outFile.length();

You should also delete the file from the cache dir when you are done with it (and the entire cache dir will also be deleted automatically when uninstalling the app).

Upvotes: 0

Michel
Michel

Reputation: 1523

test_file.available();

Is not a very reliable method to get the file length as is stated in the docs.

size = fd.getLength();

Using the FileDescriptor as shown by Ayublin is!

His answer should be promoted to the correct answer.

Upvotes: 1

ayublin
ayublin

Reputation: 1845

I have an alternative to get size of a file in assets using AssetFileDescriptor:

AssetFileDescriptor fd = getAssets().openFd("test.png");
Long size = fd.getLength();

Hope it helps.

Upvotes: 58

Related Questions