简体   繁体   中英

Direct access data in file

如何在辅助存储设备中的文件中“直接”访问第200个字符与第300个字符之间的数据?

Use a java.io.RandomAccessFile . Pseudocode:

byte[] buffer = new byte[100];
RandomAccessFile r = new RandomAccessFile("path/to/file", "r");
r.seek(200);
r.read(buffer, 0, 100);

Just add error-checking for robustness ;-)

Oh, and you said you wanted to read characters, but file operations work on bytes. If you want to read characters then you have to worry about what the file encoding is. If the encoding is something like UTF-8 then you cannot just skip to a fixed byte index, because each UTF character can encode to a variable number of bytes. In this case you will just have to read the file from the start.

看一看java.io.RandomAccessFile

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