Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to convert AssetInputStream to FileInputStream

I have implemented a data structure which is working on my computer and now I am trying to port it into my android application. I open a raw .dat resource and get a 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 code above throws the following exception since an InputStream can not be cast to a FileInputStream but that's just what I need:

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

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


Somewhat relevant posts in which I could not find a working solution for my case which android:

How to convert InputStream to FileInputStream

Converting inputStream to FileInputStream?

Using FileChannel to write any InputStream?


like image 351
Joop Avatar asked May 09 '15 10:05

Joop


People also ask

What is difference between InputStream and FileInputStream?

There is no real difference. FileInputStream extends InputStream , and so you can assign an InputStream object to be a FileInputStream object. In the end, it's the same object, so the same operations will happen. This behavior is called Polymorphism and is very important in Object-Oriented Programming.

How do I create a S3ObjectInputStream?

Use the below constructor to convert an InputStream to a S3ObjectInputStream : var s3ObjectInputStream = new S3ObjectInputStream(inputStream, null); You can safely use null for the 2nd argument in the constructor ( HttpRequestBase ) as the abort method which uses it, isn't available in the cast InputStream .

Which is the byte based input stream to read files?

FileInputStream class is useful to read data from a file in the form of sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. 1.


1 Answers

A resource isn't a file. Ergo it can't be used as a memory-mapped file. If you have resources that are so enormous they need to be memory-mapped, they probably shouldn't be resources at all. And if they are small, memory mapping brings no advantages.

like image 77
user207421 Avatar answered Sep 24 '22 00:09

user207421