tags:

views:

64

answers:

1

I have a huge set of files, to all of which there is (should be) a sentinel character (1 byte) appended to the end of file. How can I read the very last byte (to ensure it is the character) and truncate it to size (ie: remove the character)?

I know I could read the whole thing, and write it all back minus the last character, but there's got to be a way to get to a specific byte, isn't there?

+3  A: 

You can use the RandomAccessFile class to seek to the end of the file, read it, and then truncate the file using setLength().

Update: Here's some 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
}

Note: I haven't tested this code, no error handling, etc.

If the file is in any non-8-bit character set, the target.length()-1 will need to be adjusted.

HalfBrian
+1 + check for writing code, though I didn't need it. But RandomAccessFile is exactly what I was looking for.And yeah, apparently every single method in RandomAccessFile throws an IOException.
NullUserException