Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java RandomAccessFile truncate from start

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.

like image 906
retromuz Avatar asked Jan 02 '12 16:01

retromuz


People also ask

How does RandomAccessFile work in Java?

Java RandomAccessFile provides the facility to read and write data to a file. RandomAccessFile works with file as large array of bytes stored in the file system and a cursor using which we can move the file pointer position.

Which method of RandomAccessFile class reads a line from the file and return it as a String?

readLine() method reads the next line of text from this file. This method successively reads bytes from the file, starting at the current file pointer, until it reaches a line terminator or the end of the file.

What is seek method in Java?

seek(long pos) method sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs. The offset may be set beyond the end of the file. Setting the offset beyond the end of the file does not change the file length.


1 Answers

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.

like image 60
Tom Hawtin - tackline Avatar answered Sep 21 '22 22:09

Tom Hawtin - tackline