繁体   English   中英

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

在此解决方案中,必须在换行符内考虑字节数组的长度,因此您必须考虑行长来进行计算。 ->在文件中以换行符开始,在文件中以换行符结束。 长度= endInFile-startInFile +1;

暂无
暂无

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

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