从文件中读取最后一个字节并截断为大小 [英] Read last byte from file and truncate to size

查看:138
本文介绍了从文件中读取最后一个字节并截断为大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个巨大的文件集,所有这些文件(应该是)附加到文件末尾的一个哨兵字符(1字节)。我怎样才能读到最后一个字节(以确保它是字符),并截断它的大小(即:删除字符)?

我知道我可以读取整个事情,并把它写回去减去最后一个字符,但必须有一种方法来获得一个特定的字节,是不是? 解决方案

您可以使用RandomAccessFile类来查找文件末尾,读取它,然后使用 setLength()



更新:以下是一些代码:

  File target = new File(/ path / to / file); 
RandomAccessFile file = new RandomAccessFile(target,rwd);
file.seek(target.length() - 1); //设置指针到文件的末尾
char c = file.readChar();
if(c =='|')//将管道字符更改为你的哨兵字符是
{
file.setLength(target.length() - 1); //去掉最后一个_byte_,而不是最后一个字符
}

注意:没有测试这个代码,没有错误处理等。

如果这个文件是非8位字符集,那么这个目标。 length() - 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?

解决方案

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.

这篇关于从文件中读取最后一个字节并截断为大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆