簡體   English   中英

為什么不能將RandomAccessFile轉換為Inputstream?

[英]Why cant a RandomAccessFile be casted to Inputstream?

我執行此操作時出現編譯錯誤:

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

RandomAccessFile應該是InputStream子類,盡管不是直接的。

來自docs:

RandomAccessFile實現DataInput ,它包含DataInputstreamInputStream

為什么這個無效?

還要感謝您輸入使用RandomAccessFile作為InputStream的正確方法嗎?

我在想包裝方法。

使用Channels實用程序類可以輕松實現這一點......

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

RandomAccessFile擴展了Object ,並沒有擴展InputStream

如果你想從RandomAccessFile獲得一個InputStream ,我認為實現一個包裝類是你最簡單的選擇。 幸運的是, InputStream的唯一抽象方法是read()

RandomAccessFile實現DataInput,它包含DataInputstream和InputStream

DataInputStreamInputStream的子類,它也恰好實現了DataInput 繼承和接口實現樹如下所示:

           InputStream      DataInput
               \              /   \
                \            /     \
                 \          /       \
                DataInputStream   RandomAccessFile

您可以在可以使用InputStreamDataInputStream任何位置使用DataInput 您可以在可以使用DataInput任何位置使用RandomAccessFile

但是你不能在繼承層次結構中使用強制類型轉換為繼續。 特別是,將類轉換為子類(或實現的接口)將引發ClassCastException除非該對象恰好是子類的實例。

盡管兩個類碰巧擴展了Object ,但並不意味着它們可以互換。

RandomAccessFile應該擴展InputStream,盡管不是直接擴展。

不,不是。 見Javadoc。

來自docs:

RandomAccessFile實現了DataInput ,而DataInputstream又是DataInputstreamInputStream.

這根本不是“來自文檔”。 你搞定了。 你所寫的內容甚至沒有意義。 DataInput是一個接口。 DataInputStreamInputStream是類。 接口不實現或擴展類。

Javadoc實際上說的是RandomAccessFile擴展了java.lang.Object並實現了Closeable, DataInput, DataOutput

為了構建@ robert-christian的答案,使用RandomAccessFile開始的主要原因是seek某個位置,而不是從FileInputStream skip ping字節。 但那么為什么要使用前NIO API呢?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM