Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read last byte from file and truncate to size

Tags:

java

file-io

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?

like image 395
NullUserException Avatar asked Jul 21 '10 16:07

NullUserException


1 Answers

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.

like image 149
HalfBrian Avatar answered Nov 14 '22 08:11

HalfBrian