views:

525

answers:

3

Hello, me and my buddy are working on a program for our Object Oriented Programming course at college. We are trying to write text into a file as a database for information. The problem is that when we try to read the corresponding lines with BufferedReader we can't seem to figure out how to read the correct lines. The only functions avaliable seem to be read(), which reads a character only. readLine() reads only a line(not the line we want it to read. skip() only skips a number of characters specified. Anyone have an idea how we could tell the program what line we want to read? Our method getAnswer() with the argument int rowNumber is the one we are trying to do: Superclass: http://pastebin.com/d2d9ac07f Subclass is irrelevant(mostly because we haven't written it yet). Of course it is Java we are working with. Thanks beforehand.

+2  A: 

Use the Buffered Readers .readLine(); method until you get to the data you need. Throw away everything you don't and then store the data you do need. Granted this isn't effiecent it should get your job done.

Brendan
+3  A: 

You will have to use readLine(), do this in a loop, count the number of lines you've already read until you've reached the line number that you want to process.

There is no method in BufferedReader or other standard library class that will read line number N for you automatically.

Jesper
This was what we thought after a while, thanks for letting us know! Seems to be the smartest way.
Philip
Damn, you beat me by like 20 seconds :(
Brendan
+2  A: 

readLine() in Java simply reads from the buffer until it comes upon a newline character, so there would really be no way for you to specify which line should be read from a file because there is no way for Java to know exactly how long each line is.

This reason is also why it's difficult to use skip() to jump to a particular line.

It might be better for you to loop through lines using readLine(), then when your counter is where you'd like it to be, begin processing.

String line = myBufferedReader.readLine();
for(int i = 1; i < whichLine && line != null; i++){
    line = myBufferedReader.readLine();
}

/* do something */
JasonWyatt