Android - 从SDCARD读取文件而不是从缓存中读取文件
我想知道是否可以在Android中使用JAVA API从SDCARD读取文件内容。
当 pBuffer
对齐缓冲区时,我可以使用 NDK C 代码来完成此操作,
int fd = open(str, O_RDWR | O_NONBLOCK | O_DIRECT);
readCount = read(fd, pBuffer, size);
但是当我直接从 Java 使用它读取它时,
bytesRead = fin.read(originalBuffer)
它会从缓存中带来文件数据
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因此,经过长时间的调查和测试,我了解到无法直接从 Java 打开文件。
唯一的方法是使用 NDK 并使用
O_DIRECT
参数打开文件,如问题正文中所述。请注意,为了编译代码,应使用
-D_GNU_SOURCE
指令。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.我认为主要问题是在Java中获取页面对齐的内存缓冲区,以便读取文件,因为通过O_DIRECT传递文件描述符仍然可以通过JNI( http://www.kfu.com/~nsayer/Java/jni-filedesc.html - 我确实使用了这种技术能够打开Oracle Java VM for ARM 上以 UTF-8 名称命名的文件无法执行此操作,但此方法有效)。
但为了满足您的需求,我们仍然必须为系统提供一个页对齐的读操作的目标缓冲区,因为如果没有它,底层 Linux 系统在第一次尝试读取数据后会给您一个 EINVAL 错误。
我不知道有任何 Java 代码可以提供页面对齐的读取缓冲区。
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.