Why cant a RandomAccessFile be casted to Inputstream?

后端 未结 4 2057
灰色年华
灰色年华 2021-01-12 18:03

I get compilation error when I do this cast:

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

Rand

4条回答
  •  佛祖请我去吃肉
    2021-01-12 18:36

    To build on @robert-christian’s answer, the main reason to use RandomAccessFile to begin with is to seek to some position, rather than skipping bytes from a FileInputStream. But then why bother with pre-NIO APIs at all?

    try (FileChannel ch = FileChannel.open(Paths.get(…), StandardOpenOption.READ)) {
        InputStream is = Channels.newInputStream(ch.position(…));
        // …
    }
    

提交回复
热议问题