Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>I have to use Random Access Files because I need to write to different positions in file.</p> </blockquote> <p>No, you don't. You can reposition a <code>FileOutputStream</code> or <code>FileInputStream</code> via its channel.</p> <p>That would significantly simplify your writing code as well: you wouldn't need to use the buffer or channel, and depending on your needs you could omit the <code>ByteArrayOutputStream</code> as well. However, as you note in a comment, you won't know the size of the object in advance, and the <code>ByteArrayOutputStream</code> is a useful way to verify that you don't overrun your allotted space.</p> <pre><code>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() &gt; MAX_ALLOWED_SIZE) throw // or log, or whatever you want to do else { fos.getChannel().position(writeLocation); bos.writeTo(fos); } </code></pre> <p>To read the objects, do the following:</p> <pre><code>FileInputStream fis = // an initialized stream fis.getChannel().position(offsetOfSerializedObject); ObjectInputStream iis = new ObjectInputStream(new BufferedInputStream(fis)); Object obj = iis.readObject(); </code></pre> <p>One comment here: I wrapped the <code>FileInputStream</code> in a <code>BufferedInputStream</code>. In this specific case, where the file stream is repositioned before each use, that can provide a performance benefit. Be aware, however, that the buffered stream can read more bytes than are needed, and there are some situations using construct-as-needed object streams where it would be a really bad idea.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload