简体   繁体   English

直接访问文件中的数据

[英]Direct access data in file

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

Use a java.io.RandomAccessFile . 使用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. 如果编码类似于UTF-8,则您不能仅跳至固定字节索引,因为每个UTF字符都可以编码为可变数目的字节。 In this case you will just have to read the file from the start. 在这种情况下,您只需要从头开始读取文件。

看一看java.io.RandomAccessFile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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