简体   繁体   中英

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. 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. 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. It can be done with Java?

Roberto

Use a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM