Search code examples
javarandomaccessfile

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.

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.

For example i have a huge file and i want to read text from index 100 to index 500, i would start like this:

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 :)


Solution

  • 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.

    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;