× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

FileChannel returns wrong file size of file in assets folder

Xaver Kapeller
May 29, 2015
<p>When your app is compiled all resources are packaged together into what is essentially one big <code>File</code>. To get just the data of the one <code>File</code> you want to read you have to use <code>getStartOffset()</code> and <code>getDeclaredLength()</code> of the <code>AssetFileDescriptor</code>. From the <a href="http://developer.android.com/reference/android/content/res/AssetFileDescriptor.html" rel="nofollow"><strong>documentation</strong></a>:</p> <blockquote> <ul> <li><code>getStartOffset()</code>: Returns the byte offset where this asset entry's data starts.</li> <li><code>getDeclaredLength()</code>: Return the actual number of bytes that were declared when the AssetFileDescriptor was constructed. Will be <a href="http://developer.android.com/reference/android/content/res/AssetFileDescriptor.html#UNKNOWN_LENGTH" rel="nofollow">UNKNOWN_LENGTH</a> if the length was not declared, meaning data should be read to the end of the file.</li> </ul> </blockquote> <hr> <p>So instead of just reading the whole <code>File</code> from start to finish you just need to read the data starting at the index returned by <code>getStartOffset()</code> and you need to read as many bytes as are returned by <code>getDeclaredLength()</code>. Try something like this:</p> <pre><code>long startOffset = fileDescriptor.getStartOffset(); long declaredLength = fileDescriptor.getDeclaredLength(); MappedByteBuffer mappedByteBuffer = fileChannel.map( FileChannel.MapMode.READ_ONLY, startOffset, declaredLength); </code></pre> <p>If you want to account for the case in which <code>getDeclaredLength()</code> returns <code>UNKNOWN_LENGTH</code> you can just do this:</p> <pre><code>if(declaredLength == AssetFileDescriptor.UNKNOWN_LENGTH) { declaredLength = fileChannel.size() - startOffset; } </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/30395744/FileChannel%20returns%20wrong%20file%20size%20of%20file%20in%20assets%20folder/30396644">Stack Overflow</a>.</p>
comments powered by Disqus