I need to use random access files because I need to write for different positions in the file.
No no. You can move FileOutputStream or FileInputStream through your channel.
This will greatly simplify your recording code: you will not need to use a buffer or channel, and depending on your needs, you can also omit ByteArrayOutputStream . However, as you noted in the comment, you wonโt know the size of the object in advance, and ByteArrayOutputStream is a useful way to verify that you are not overflowing the allocated space.
Object obj = // something FileOutputStream fos = // an initialized stream ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(obj); oos.flush(); if (bos.size() > MAX_ALLOWED_SIZE) throw // or log, or whatever you want to do else { fos.getChannel().position(writeLocation); bos.writeTo(fos); }
To read objects, do the following:
FileInputStream fis = // an initialized stream fis.getChannel().position(offsetOfSerializedObject); ObjectInputStream iis = new ObjectInputStream(new BufferedInputStream(fis)); Object obj = iis.readObject();
One comment here: I wrapped FileInputStream in a BufferedInputStream . In this particular case, when the file stream is moved before each use, this can provide a performance advantage. Keep in mind, however, that a buffered stream can read more bytes than necessary, and there are situations where object streams that are needed as objects are used where it would be a very bad idea.
source share