使用RandomAccessFile java读取文件中的特定索引

问题描述 投票:2回答: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;
}

请帮我 :)

java randomaccessfile
1个回答
-1
投票

这就是我解决问题的方法:

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();
}

在此解决方案中,必须在换行符中考虑bytes数组的长度,因此必须考虑行长度来计算。 - >在带有换行符的文件中启动,并在文件中使用换行符结束索引。 length = endInFile-startInFile +1;

© www.soinside.com 2019 - 2024. All rights reserved.