Read last byte from file and truncate to size

I have a huge set of files for which there is (should be) a sentinel character (1 byte) added at the end of the file. How can I read the last byte (to make sure it is a character) and truncate it to size (i.e. delete the character)?

I know that I could read all this, and write everything back minus the last character, but there should be a way to get a specific byte, right?

+5
source share
1 answer

You can use the RandomAccessFile class to find the end of a file, read it, and then trim the file with setLength().

Update: Here is the code:

File target = new File("/path/to/file");
RandomAccessFile file = new RandomAccessFile(target,"rwd");
file.seek(target.length()-1); // Set the pointer to the end of the file
char c = file.readChar();
if(c == '|') // Change the pipe character to whatever your sentinel character is
{
     file.setLength(target.length()-1); // Strip off the last _byte_, not the last character
}

. , ..

8- , target.length()-1.

+11

All Articles