Android中如何正确获取Assets目录下BIN文件的大小?
Hey there! I see you're having trouble getting the actual size of a .bin file from your Android assets directory—your current code works for ZIP files but returns 0 for BIN files when using available(). Let's break down why this happens and fix it.
Why available() Isn't Working
The InputStream.available() method doesn't return the total size of the asset. It only tells you how many bytes you can read right now without blocking the current thread. For ZIP files, their internal structure might let this method return a usable number by coincidence, but binary files like .bin don't have that metadata, so it often returns 0.
Correct Ways to Get the BIN File Size
1. Use AssetFileDescriptor (Recommended)
This is the most reliable way to get the exact size of any asset file. AssetFileDescriptor gives you direct access to the asset's underlying file details, including its full length:
try { // Open the asset file descriptor AssetFileDescriptor afd = context.getAssets().openFd("test.bin"); // Get the exact file size long fileSize = afd.getLength(); afd.close(); // If you need to read the file content afterward InputStream is = context.getAssets().open("test.bin"); byte[] buffer = new byte[(int) fileSize]; is.read(buffer); is.close(); // Now fileSize holds the correct size of your test.bin } catch (Exception e) { throw new RuntimeException(e); }
2. Calculate Size by Reading the Stream (For Large Files)
If your .bin file is extremely large (large enough that loading it all into a byte array would cause memory issues), you can calculate the size by reading the stream in chunks:
try { InputStream is = context.getAssets().open("test.bin"); long fileSize = 0; byte[] tempBuffer = new byte[1024]; // Use a 1KB buffer for reading int bytesRead; // Read until the stream ends while ((bytesRead = is.read(tempBuffer)) != -1) { fileSize += bytesRead; } is.close(); // fileSize now has the total size of the BIN file } catch (Exception e) { throw new RuntimeException(e); }
Quick Note on Large Files
If your .bin file is very big, avoid loading the entire file into a single byte[]—this can trigger an OutOfMemoryError. Instead, process the file in smaller chunks as you read it.
内容的提问来源于stack exchange,提问作者TsigumEnes

