Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes, use <code>RandomAccessFile</code> - that's what it's there for. You <em>could</em> potentially use a <code>FileChannel</code>, but I'd go for <code>RandomAccessFile</code> first - it's likely to be simpler.</p> <p>Note that you won't be able to "insert in the middle" of the file after writing the end part: I don't know any file system which supports that. You'll need to know the complete size before you write the final section, basically. An alternative would be to write sequentially, remembering the final bit until the end.</p> <p>If you can give us more information about what you need to do (and when you have information about the size) we may be able to help you more.</p> <p>EDIT: To create the file with a specific size,you can <code>seek()</code> past the end and then write data:</p> <pre><code>import java.io.*; public class Test { // Just for the sake of a simple test program! public static void main(String[] args) throws Exception { RandomAccessFile file = new RandomAccessFile("file.dat", "rw"); file.seek(100); file.write(0); file.close(); } } </code></pre> <p>After this has exited, <code>file.dat</code> will be 101 bytes long. (Note that normally you'd use try/finally etc.)</p> <p>EDIT: As coobird mentioned in the comments, <code>setLength()</code> will also extend the file - but it will also truncate the file if you give a length less than the current size. Given your comment about basically writing torrent data, I suspect that seeking and then writing is exactly the behaviour you want. When you receive a chunk, just seek to the right spot, write it out, and the file will extend itself when it needs to.</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