[英]read until specific index in a file with RandomAccessFile java
I was trying to read from a file between two specific indices using the RandomAccessFile. 我试图使用RandomAccessFile从两个特定索引之间的文件中读取。
I know I can jump to an index with the seek()
function, but i couldn't find the answer how to read then text out of the file until a specific index. 我知道我可以使用
seek()
函数跳转到索引,但是在找到特定索引之前,我找不到如何从文件中读取文本的答案。
For example i have a huge file and i want to read text from index 100 to index 500, i would start like this: 例如,我有一个巨大的文件,我想从索引100到索引500读取文本,我将这样开始:
public String get_text(){
raf.seek(100) //raf= my RandomAccessFile
String txt=raf.read(500) //read until index 500 which i don't know how to do
return txt;
}
Please help me :) 请帮我 :)
This is how I solved my Problem: 这是我解决问题的方式:
try {
int index = 100;
raf.seek(index); //index = 100
int counter = 0;
int length = 400;
while (counter < length) { //want to read the characters 400 times
char c = (char) raf.read();
if (!(c == '\n')) { //don't append the newline character to my result
sb.append(c); //sb is a StringBuilder
counter++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
I saw also another solution, where readFully() was used with a bytes array, that also worked well. 我还看到了另一种解决方案,其中readFully()与字节数组一起使用,效果也很好。
try {
raf.seek(index);
byte[] bytes = raf.readFully(new byte[(int) length]); //length of the charactersequence to be read
String str = bytes.toString();
} catch (IOException e){
e.printStackTrace();
}
In this solution the length of the bytes array has to be considered within the newline character, so you have to calculate that considering the line length. 在此解决方案中,必须在换行符内考虑字节数组的长度,因此您必须考虑行长来进行计算。 ->Start in file with line breaks and end index in file with line breaks.
->在文件中以换行符开始,在文件中以换行符结束。 length = endInFile-startInFile +1;
长度= endInFile-startInFile +1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.