tags:

views:

76

answers:

1

I've to be continuously editing a 1MB file, simulating a file system. I've to modify the directory of File Control Blocks, FAT, blocks, etc.

Proffesor recommended overwriting the file every time an update is made. 1MB shouldn't take minutes to do that, but I don't like this way.

Is it a FileChannel the way to go here? Also, I understand that if I edit a MappedByteBuffer, the content of the mapped file region is also edited immediately? i.e. is reflexive mapped?

Thanks.

+1  A: 

You need RandomAccessFile.

Chris Dennett
The problem I see with RandomAccessFile is that the only way to be overwriting data is: 1. Write X bytes in position P (prepended to the data i want to overwrite)2. Write all the rest of the file beggining from P+X3. Truncate the file Isn't it ugly?
kmels
You can seek to any position and then write to that position. The rest is up to you. You need knowledge of how your filesystem resides on the disk, using in-memory objects with seek offsets in the file for when writing is to take place. You can also get a file channel using the getChannel() method.
Chris Dennett
It looks like MappedByteBuffer is quite good as well, and also allows you to seek. There doesn't seem to be much difference. You can also use MappedByteBuffer with stuff that expects a ByteBuffer. I think that either of these approaches shouldn't rewrite the entire file when a write is made. It'd be too inefficient.
Chris Dennett
http://www.java2s.com/Code/Java/File-Input-Output/Writetoamappedfile.htm
Chris Dennett
@kmels I don't understand your problem with overwriting data. The usual way is: 1. Seek to the position you want to start overwriting 2. overwrite. You cannot _insert_ into a RandomAccessFile nor _remove_ content before the end, only _overwrite_ data, _append_ at the end or _truncate_ the file.
Christian Semrau
You are right Christian, i just checked that, although FileChannel.map has solved the problem nicely too. Thanks for your answers.
kmels