Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RandomAccessFile-like API for in-memory byte array?

Tags:

java

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?

like image 821
Konrad Garus Avatar asked Feb 04 '11 11:02

Konrad Garus


People also ask

What is the use of RandomAccessFile?

Java RandomAccessFile provides the facility to read and write data to a file. RandomAccessFile works with file as large array of bytes stored in the file system and a cursor using which we can move the file pointer position.

What is RandomAccessFile in Java?

RandomAccessFile(File file, String mode) Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. RandomAccessFile(String name, String mode) Creates a random access file stream to read from, and optionally to write to, a file with the specified name.

Which method is used in RandomAccessFile class to get the current location of the file pointer?

readFloat() : java. io. RandomAccessFile. readFloat() reads a float value from the file, start reading from the File Pointer.

What is the difference between the file and RandomAccessFile classes?

File is an abstract representation of a file/directory which may or may not even exist. It doesn't consume any resources, so you can store them as much as you want. RandomAccessFile is for actual file access (reading, seeking, writing), so you don't need it here.


2 Answers

ByteArrayInputStream can do it:

  • read() works the same.
  • seek(n) can be replaced with reset() followed by skip(n)
like image 189
Konrad Garus Avatar answered Nov 05 '22 06:11

Konrad Garus


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

like image 41
Ahmad Y. Saleh Avatar answered Nov 05 '22 05:11

Ahmad Y. Saleh