[英]Access the same file for read and write random position
Start by saying that I have not great experience in Java and I've done a lot of research. 首先,我没有Java方面的丰富经验,并且做了很多研究。 I would please ask you a specific question.
请问一个具体问题。 Thank you
谢谢
I need to open a file for reading and writing from which I read and write a 512-byte blocks. 我需要打开一个文件进行读写,并从中读写512字节的块。 The file is fixed length and the information to be written will overlap with other existing.
该文件是固定长度的,并且要写入的信息将与其他现有信息重叠。 For example, I read the first 512 bytes of the file and if it contains certain values write a block 512 to position 2048. I tried using
FileInputStream
and FileOutputStream
but every time I open with FileOutputStream
the contents of the file are deleted. 例如,我读取了文件的前512个字节,如果文件中包含某些值,则将512块写入位置2048。我尝试使用
FileInputStream
和FileOutputStream
但每次使用FileOutputStream
打开时,文件的内容都会被删除。 It can be done with Java? 可以用Java完成吗?
Roberto 罗伯托
Use a FileChannel
; 使用
FileChannel
; it allows random access to any part of a file, in read, write or any combination of both. 它允许以读取,写入或两者的任意组合随机访问文件的任何部分。
Example: 例:
final Path path = Paths.get("path/to/the/file");
final FileChannel channel = FileChannel.open(path, relevantOptions);
Optionally, after that, you can use the .map()
method. (可选)在那之后,您可以使用
.map()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.