Konrad Garus
Konrad Garus

Reputation: 54025

RandomAccessFile-like API for in-memory byte array?

I need to replace code using RandomAccessFile with one that uses in-memory byte buffer (such as byte[] or derivatives like ByteArrayInputStream). Is there some API (byte array wrapper?) that has interface similar to RandomAccessFile, with seek() and streamish read() which I could plug in one-to-one?

Upvotes: 11

Views: 4445

Answers (4)

Vouze
Vouze

Reputation: 1784

I had the same problem. RandomAccessFile has many finale and native methods, so it cannot be overloaded.

I ended to create my own SeekableInputStream abstract class by stealing this one without readfully : https://github.com/samtools/htsjdk/blob/master/src/java/htsjdk/samtools/seekablestream/SeekableStream.java

I defined SeekableFileInputStream which uses RandomAccessFile.

I defined SeekableByteArrayInputStream, which is easy to define. This class, is also able to get any InputStream, to transform it into a byte array, so this is a kind of cached stream.

Upvotes: 0

Konrad Garus
Konrad Garus

Reputation: 54025

ByteArrayInputStream can do it:

  • read() works the same.
  • seek(n) can be replaced with reset() followed by skip(n)

Upvotes: 10

Ahmad Y. Saleh
Ahmad Y. Saleh

Reputation: 3349

May I suggest Java NIO (New I/O) check this simple and small tutorial

Upvotes: 3

joriki
joriki

Reputation: 651

I happen to have one of these -- I uploaded it to http://home.arcor.de/joriki/seekable-byte-array.zip -- hope that helps.

Upvotes: -1

Related Questions