Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cant a RandomAccessFile be casted to Inputstream?

Tags:

java

java-io

I get compilation error when I do this cast:

RandomAccessFile raf = new RandomAccessFile(...)
InputStream is = (InputStream)raf;

RandomAccessFile is supposed to subclass InputStream although not directly.

From docs:

RandomAccessFile implements DataInput which inturn DataInputstream & InputStream

Why is this invalid?

Also appreciate your input on what would be the right way to use the RandomAccessFile as InputStream?

I am thinking of wrapper approach.

like image 799
PS1 Avatar asked Feb 15 '12 03:02

PS1


1 Answers

This is easily achievable using the Channels utility class...

// STEP 1:  Create random access file read-only
RandomAccessFile raf = new RandomAccessFile("/text.txt", "r");

// STEP 2:  Use Channels to convert to InputStream
InputStream is = Channels.newInputStream(raf.getChannel());
like image 158
Robert Christian Avatar answered Oct 07 '22 01:10

Robert Christian