使用 RandomAccessFile java 读取文件中的特定索引
read until specific index in a file with RandomAccessFile java
我试图使用 RandomAccessFile 从两个特定索引之间的文件中读取。
我知道我可以使用 seek()
函数跳转到一个索引,但是我找不到如何从文件中读取文本直到特定索引的答案。
例如我有一个大文件,我想从索引 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;
}
请帮助我:)
这就是我解决问题的方法:
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();
}
我还看到了另一个解决方案,其中 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();
}
在此解决方案中,必须在换行符内考虑字节数组的长度,因此您必须考虑行长度来计算它。
-> 在文件中以换行符开始,在文件中以换行符结束索引。 length = endInFile-startInFile +1;
我试图使用 RandomAccessFile 从两个特定索引之间的文件中读取。
我知道我可以使用 seek()
函数跳转到一个索引,但是我找不到如何从文件中读取文本直到特定索引的答案。
例如我有一个大文件,我想从索引 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;
}
请帮助我:)
这就是我解决问题的方法:
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();
}
我还看到了另一个解决方案,其中 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();
}
在此解决方案中,必须在换行符内考虑字节数组的长度,因此您必须考虑行长度来计算它。 -> 在文件中以换行符开始,在文件中以换行符结束索引。 length = endInFile-startInFile +1;