Search code examples
javarandom-access

Is it possible to set a speicifc byte in a RandomAccessFile back to null?


Origianlly, when I created the RandomAccessFile, I skipped over some bytes so those stayed as null, but now I need to delete some of the bytes I wrote. Right now, what I'm doing is overwriting the location with a space, but is there a way to set it back to empty?

EDIT: Since It has to contain a value, I would like to know how to set it back to the original value that it is assigned by default when it is skipped.


Solution

  • A file cannot contain an "empty" byte. Each byte in the file must have a value between 0 and 255.

    If you want to "erase" all bytes after a certain point, you could use RandomAccessFile.setLength which truncates the file.


    Regarding your comment: If you want to set some bytes back to it's original value, I suggest you encapsulate a RandomAccessFile in your own class with a map from index to original byte value, which you update in each call to write. This subclass could then provide a method restore(int i) that restores the value of the byte at index i by looking up the original value in the map.