Reputation: 101
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());
}
}
Upvotes: 2
Views: 4773
Reputation: 1
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();
Upvotes: 0
Reputation: 425
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.
Upvotes: 2
Reputation: 9331
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);
}
Upvotes: 6