2

I am reading 10 lines from a simple RandomAccessFile and printing each line. The exact lines in the text file are as follows one after the other:

blue

green

bubble

cheese

bagel

zipper

candy

whale

monkey

chart

When printing them in order as I read line by line my output is this:

green

cheese

zipper

whale

chart

I cannot understand why my method is skipping every other line in the file. Am I misunderstanding how a RandomAccessFile works? My method is below:

RandomAccessFile file = new RandomAccessFile(FILEPATH, "rw");
    read(file);

public static void read(RandomAccessFile t) throws IOException{
    while (t.readLine()!=null) {
        System.out.println(t.readLine());
    }
}
Branbron
  • 101
  • 4
  • 12
  • when you use readLine the pointer in the file jump to the next position, so when you use it twice, one in while, and also in the print, you jump in the while and after you print the second value. – Pedro Molina Mar 27 '21 at 17:05

3 Answers3

6

You are calling readLine() twice

while (t.readLine()!=null) {
    System.out.println(t.readLine());
}

Instead precompute the readLine();

String tmp;
while((tmp = t.readLine()) != null) {
    System.out.println(tmp);
}
gtgaxiola
  • 9,241
  • 5
  • 42
  • 64
2

Try this:

   String line = null;
    while ((line = br.readLine()) != null) {
    System.out.println(line);
    }

Every time you call readlin() it goes to next line that is why you are getting only even lines printed.

Dipen Adroja
  • 415
  • 5
  • 15
0

While using RandomAccessFile you could read at any seek position too rather than going line by line for optimized I/O performance.

RandomAccessFile raf = new RandomAccessFile("file","r");

raf.seek(info.getStartingIndex());//Maintain info while serializing obj
byte[] bytes = new byte[info.getRecordLength()];//length stored earlier similarly 
raf.read(bytes);
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();