【问题标题】:read until specific index in a file with RandomAccessFile java使用 RandomAccessFile java 读取文件中的特定索引
【发布时间】:2019-01-17 16:20:50
【问题描述】:

我试图使用 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】:

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

    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;

    【讨论】:

    • 第二种解决方案应该使用readFully()。否则无法保证缓冲区已被填满。
    • hmm,如果我查看 JavaDocs docs.oracle.com/javase/7/docs/api/java/io/… read() 没有看到更多异常捕获...你能解释为什么缓冲区无法被填充?
    • 因为在read()的合同中并没有说填写。这就是它返回计数的原因。另一方面,readFully() 保证填充缓冲区或抛出EOFException 或另一个IOException,或者阻塞直到其中一个发生。您答案中的read() 方法既不是这些,也没有提供,这使您的答案充其量是不完整的。
    • @user207421 现在我明白了,谢谢,我会更正它。 read() 不会抛出 EOFException 但会抛出 IOExceptions: IOException - 如果第一个字节由于文件结尾以外的任何原因无法读取,或者如果随机访问文件已关闭,或者如果发生其他一些 I/O 错误。
    • 我不知道你为什么要告诉我这个。我知道这个。这就是我要告诉你的。它返回一个计数,而不是抛出EOFException。这就是我想说的。尤其是当您忽略计数时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多