我已经实现了一个可以在我的电脑上运行的数据结构,现在我正试图将它移植到我的 android 应用程序中。我打开原始 .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
?
一些相关的帖子,我在其中找不到适用于我的案例的工作解决方案 which android:
How to convert InputStream to FileInputStream
Converting inputStream to FileInputStream?
Using FileChannel to write any InputStream?
最佳答案
资源不是文件。因此,它不能用作内存映射文件。如果您拥有大量需要内存映射的资源,那么它们可能根本不应该是资源。如果它们很小,内存映射就没有优势。
关于java - 需要将 AssetInputStream 转换为 FileInputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30138830/