简体   繁体   中英

Android - read file from SDCARD not from cache

I'd like to know if it possible to read the content of file from SDCARD using JAVA API in Android.
I can do it using NDK C code by

int fd = open(str, O_RDWR | O_NONBLOCK | O_DIRECT);  
readCount = read(fd, pBuffer, size); 

when pBuffer is aligned buffer but when I read it using directly from Java using

bytesRead = fin.read(originalBuffer)

It brings file data from cache

So after long investigation and test I understand there is no way to open file directly from Java.
The only way to do it is to use NDK and open the file using O_DIRECT parameter as explained in the body of the question.
Note that in order to compile the code -D_GNU_SOURCE directive should be used.

I think that the main problem is to get a page aligned memory buffer in Java, in order to read the file, because passing the file descriptor with O_DIRECT is still possible through JNI ( http://www.kfu.com/~nsayer/Java/jni-filedesc.html - I did use this technique to be able to open file named with UTF-8 names on the Oracle Java VM for ARM which can't do that and this works).

But to fulfill your needs we still have to provide to the system a destination buffer for the read operation which is page aligned, because without it the underlying linux system gives you an EINVAL error after the first try to read data.

I'm not aware of any Java code which can provide page aligned read buffer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM