Read last byte from file and truncate to size

前端 未结 1 1671
天命终不由人
天命终不由人 2021-01-02 22:49

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 i

相关标签:
1条回答
  • 2021-01-02 23:41

    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.

    0 讨论(0)
提交回复
热议问题