删除Java中随机访问文件的第一个字节

时间:2022-10-07 20:22:06

I'm writing bytes to a random access file. After completing the operation, I want to delete the first 100 bytes from the file. How can I achieve this?

我正在将字节写入随机访问文件。完成操作后,我想从文件中删除前100个字节。我怎样才能做到这一点?

Thanks in advance.

提前致谢。

3 个解决方案

#1


4  

AFAIK, you will need to copy the remaining bytes (file length - 100) to a new file. Deleting the first 100 bytes from a file is not possible without copying the remaining bytes to a new file.

AFAIK,您需要将剩余的字节(文件长度 - 100)复制到新文件。如果不将剩余字节复制到新文件,则无法从文件中删除前100个字节。

Edit: As cdhowie rightly pointed out, you could:

编辑:正如cdhowie正确指出的那样,你可以:

  • seek to 100,
  • 寻求100,

  • read X amount of bytes (more than 100 though)
  • 读取X字节数(虽然超过100)

  • seek to 0,
  • 寻求0,

  • write X amount of bytes
  • 写X字节数

Then repeat the process until the entire file is written. Finish off by setting the filelength 100 bytes less than previously. If you want to be on the safe side and not risk corrupting the original file, it could be worth writing to a temp file first.

然后重复该过程,直到写入整个文件。通过将文件长度设置为比以前少100个字节来完成。如果您想要安全起见而不冒破坏原始文件的风险,那么首先要写入临时文件是值得的。

#2


5  

i found a method which provides the desired works. it's deleteRAF and here.

我找到了一种提供所需工作的方法。这是删除RAF和这里。

thanks your advices.

谢谢你的建议。

#3


0  

There is no simple way to do this. You will have to read starting from byte 100 and write starting from byte 0 -- essentially, shift the file contents down by 100 bytes manually. Then you can truncate the file to 100 bytes less than its length.

没有简单的方法可以做到这一点。您必须从字节100开始读取并从字节0开始写入 - 实际上,手动将文件内容向下移动100个字节。然后,您可以将文件截断为小于其长度的100个字节。

#1


4  

AFAIK, you will need to copy the remaining bytes (file length - 100) to a new file. Deleting the first 100 bytes from a file is not possible without copying the remaining bytes to a new file.

AFAIK,您需要将剩余的字节(文件长度 - 100)复制到新文件。如果不将剩余字节复制到新文件,则无法从文件中删除前100个字节。

Edit: As cdhowie rightly pointed out, you could:

编辑:正如cdhowie正确指出的那样,你可以:

  • seek to 100,
  • 寻求100,

  • read X amount of bytes (more than 100 though)
  • 读取X字节数(虽然超过100)

  • seek to 0,
  • 寻求0,

  • write X amount of bytes
  • 写X字节数

Then repeat the process until the entire file is written. Finish off by setting the filelength 100 bytes less than previously. If you want to be on the safe side and not risk corrupting the original file, it could be worth writing to a temp file first.

然后重复该过程,直到写入整个文件。通过将文件长度设置为比以前少100个字节来完成。如果您想要安全起见而不冒破坏原始文件的风险,那么首先要写入临时文件是值得的。

#2


5  

i found a method which provides the desired works. it's deleteRAF and here.

我找到了一种提供所需工作的方法。这是删除RAF和这里。

thanks your advices.

谢谢你的建议。

#3


0  

There is no simple way to do this. You will have to read starting from byte 100 and write starting from byte 0 -- essentially, shift the file contents down by 100 bytes manually. Then you can truncate the file to 100 bytes less than its length.

没有简单的方法可以做到这一点。您必须从字节100开始读取并从字节0开始写入 - 实际上,手动将文件内容向下移动100个字节。然后,您可以将文件截断为小于其长度的100个字节。