Why cant a RandomAccessFile be casted to Inputstream?

PS1 picture PS1 · Feb 15, 2012 · Viewed 10.8k times · Source

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.

Answer

Robert Christian picture Robert Christian · Jan 29, 2015

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());