我已经实现了一个在我的电脑上运行的数据结构,现在我正在尝试将它移植到我的安卓应用程序中。我打开一个原始的.dat
资源并获取了一个InputStream
,但我需要获取一个FileInputStream
:
FileInputStream fip = (FileInputStream) context.getResources().openRawResource(fileID);
FileChannel fc = fip.getChannel();
long bytesSizeOfFileChannel = fc.size();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0L, bytesSizeOfFileChannel);
...
由于InputStream不能强制转换为FileInputStream,上述代码会抛出以下异常,但这正是我所需要的:
java.lang.ClassCastException: android.content.res.AssetManager$AssetInputStream cannot be cast to java.io.FileInputStream
我的所有代码都是基于使用
FileChannel
和FileInputStream构建的,因此我想继续使用它。有没有一种方法可以从context.getResources().openRawResource(fileID)
获得一个InputStream
,然后将其转换为FileChannel
?
以下是与我的情况相关但无法找到可行解决方案的帖子: 如何将InputStream转换为FileInputStream? 将InputStream转换为FileInputStream? 使用FileChannel写入任何InputStream?
MappedByteBuffer
来读取文件是最快的。而Android并不运行Java 6 JVM,也不会读取文件。Android运行的是Dalvik VM或者ART(取决于Android版本),而你是在读取asset(基本上就是ZIP文件中的一个条目)。因此,该文章的内容大部分都是无关紧要的。 - CommonsWare