从文件中读取最后一个字节并截断为大小
我有一大堆文件,所有文件都应该(应该是)附加到文件末尾的标记字符(1个字节)。 如何读取最后一个字节(以确保它是字符)并将其截断为大小(即:删除字符)?
我知道我可以阅读整个内容,然后将它全部写回去减去最后一个字符,但必须有一种方法来获取特定的字节,不是吗?
您可以使用RandomAccessFile类来搜索文件的末尾,读取它,然后使用setLength()
截断文件。
更新:这是一些代码:
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 }
注意:我没有测试过此代码,没有error handling等。
如果文件是任何非8位字符集,则需要调整target.length()-1
。