Need to convert AssetInputStream to FileInputStream

I have implemented a data structure that works on my computer, and now I'm trying to transfer it to my Android application. I open the source .dat resource and get an InputStream , but I need to get a 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); ... 

The following exception is thrown in the code above, since InputStream cannot be passed to FileInputStream, but this is what I need:

 java.lang.ClassCastException: android.content.res.AssetManager$AssetInputStream cannot be cast to java.io.FileInputStream 

All my code is built using this FileChannel with FileInputStream, so I want to keep using it. Is there a way to go from InputStream from context.getResources().openRawResource(fileID) and then convert it to FileChannel ?


A few important posts in which I could not find a working solution for my case, which is android:

How to convert InputStream to FileInputStream

Convert inputStream to FileInputStream?

Using FileChannel to write any InputStream?


+5
source share
2 answers

The resource is not a file. Ergo cannot be used as a memory mapped file. If you have such huge resources, they should be mapped into memory, they probably shouldn't be resources at all. And if they are small, displaying memory does not give any advantages.

+6
source

It may be late, but I think you can indirectly get a FileInputStream from an InputStream. I suggest the following: get the input stream from the resource, then create a temporary file, get FileOutputStream from it. read InputStream and copy it to FileOutputStream.

now the temp file contains the contents of your resource file, and now you can create a FileInputStream from this file.

I don't know if this particular solution is right for you, but I think it can be used in other situations. For example, if your file is located in the resource folder, you get an InputStream and then a FileInputStream using this method:

 InputStream is=getAssets().open("video.3gp"); File tempfile=File.createTempFile("tempfile",".3gp",getDir("filez",0)); FileOutputStream os=newFileOutputStream(tempfile); byte[] buffer=newbyte[16000]; int length=0; while((length=is.read(buffer))!=-1){ os.write(buffer,0,length); } FileInputStream fis=new FileInputStream(tempfile); 
0
source

All Articles