tags:

views:

99

answers:

3

I want to read in the 1st, 4th, 7th, etc. (every 3 lines) from a text file but am not sure how to go about doing so as nextLine() reads everything sequentially. Thank you for your suggestions?

Scanner in2 = new Scanner(new File("url.txt"));

while (in2.hasNextLine()) {
    // Need some condition here
    String filesURL = in2.nextLine();
}
+2  A: 

If you don't already have an index that tells you the file offset where each line begins in the file, then the only way to find each line is to read the file sequentially.

Are you sure the objective is not just to /output/ the 1st, 4th, 7th, etc lines? You can read all lines sequentially but keep only the ones you're interested in.

dthorpe
+8  A: 

Use a counter, and the % (modulus) operator so only every third line is read.

Scanner in = new Scanner(new File("url.txt"));

int i = 1;

while (in.hasNextLine()) {
    // Read the line first
    String filesURL = in.nextLine();

    /*
     * 1 divided by 3 gives a remainder of 1
     * 2 divided by 3 gives a remainder of 2
     * 3 divided by 3 gives a remainder of 0
     * 4 divided by 3 gives a remainder of 1
     * and so on...
     * 
     * i++ here just ensures i goes up by 1 every time this chunk of code runs.
     */
    if (i++ % 3 == 1) {
        // On every third line, do stuff; here I just print it
        System.out.println(filesURL);
    }
}
BoltClock
+1 nice, but way to ruin an education. Oh well, at least I'll still be getting paid...
karim79
@karim79: I commented my code to explain how the operator works, if that helps...
BoltClock
Err, that will only read a line every third time through the loop and either process every line once (if the processing is within the `if`) or process every line three times (if it's outside the `if`).
paxdiablo
@BoltClock - I was just being (silly?) I thought your code was self-explanatory.
karim79
Thank you for the comments! I really helped me to understand the logic.
@paxdiablo: oops! I've fixed it now.
BoltClock
That's better. +1 though this is _not_ the start of a mutual admiration society :-)
paxdiablo
@paxdiablo: I'll take your word for it ;)
BoltClock
@paxdiablo - can I join? :-) :-)
Stephen C
+5  A: 

You read every line but only process every third one:

int lineNo = 0;
while (in2.hasNextLine()) {
    String filesURL = in2.nextLine();
    if (lineNo == 0)
        processLine (filesURL);
    lineNo = (lineNo + 1) % 3;
}

The lineNo = (lineNo + 1) % 3 will cycle lineNo through 0,1,2,0,1,2,0,1,2,... and lines will only be processed when it's zero (so lines 1, 4, 7, ...).

paxdiablo
+1 for spotting the error in my answer and providing the right code :)
BoltClock