6

I know how to truncate a RandomAccess file so that bytes at the end are removed.

raf.getChannel().truncate(file.length() - 4);

or

raf.setLength(file.length() - 4);

But how to truncate a RandomAccessFile in such a way that bytes at the start is removed? I don't need to write contents of this file to a new file. I googled and could not find an answer. Please help. Thanks in advance.

user207421
  • 305,947
  • 44
  • 307
  • 483
retromuz
  • 809
  • 9
  • 26

1 Answers1

8

It's not an operation most file systems support. The model is a sequence of bytes starting at a particular place on the disc. Files are variable length and can be appended, and so truncation is relatively easy from there.

So you will actually need to copy all the bytes in the file. If at all possible avoid. One technique to manage queue files (such as logs), is to have a sequence of files then start a new file periodically and drop one off the end.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • Thanks for the heads up @Tom. I went ahead with the following using your information. fc.transferTo(seek, file.length() - seek, fcTmp); – retromuz Jan 03 '12 at 04:50
  • it's too bad, too. filesystems running on flash media would be ideal for a "truncate from beginning" due to the limited number of erase cycles. – Michael Apr 01 '13 at 03:43