user3409084
user3409084

Reputation: 3

Java: Two Scanners reading from the same input file. Doable? Useful?

I have to read in integers from an input file based on whether or not a string that appears before them is a certain keyword "load". There is no key number telling how many numbers are about to be inputted. These numbers must be saved to an array. In order to avoid creating and updating a new array for each additional number scanned, I'd like to use a second scanner to first find the amount of integers, and then have the first scanner scan that many times before reverting back to testing for strings. My code:

public static void main(String[] args) throws FileNotFoundException{
    File fileName = new File("heapops.txt");
    Scanner scanner = new Scanner(fileName);
    Scanner loadScan = new Scanner(fileName);
    String nextInput;
    int i = 0, j = 0;
    while(scanner.hasNextLine())
    {
        nextInput = scanner.next();
        System.out.println(nextInput);
        if(nextInput.equals("load"))
        {
            loadScan = scanner;

            nextInput = loadScan.next();
            while(isInteger(nextInput)){
                i++;
                nextInput = loadScan.next();
            }

            int heap[] = new int[i];
            for(j = 0; j < i; j++){
                nextInput = scanner.next();
                System.out.println(nextInput);
                heap[j] = Integer.parseInt(nextInput);
                System.out.print(" " + heap[j]);
            }
        }




    }

    scanner.close();
}

My problem seems to be that scanning via loadscan, the secondary scanner only meant for integers, also moves the primary scanner forward. Is there any way to stop this from happening? Any way to make the compiler treat scanner and loadscan as separate objects despite them preforming the same task?

Upvotes: 0

Views: 5801

Answers (1)

Rainbolt
Rainbolt

Reputation: 3660

You may certainly have two Scanner objects read from the same File object simultaneously. Advancing one will not advance the other.

Example

Assume that the contents of myFile are 123 abc. The snippet below

    File file = new File("myFile");
    Scanner strFin = new Scanner(file);
    Scanner numFin = new Scanner(file);
    System.out.println(numFin.nextInt());
    System.out.println(strFin.next());

... prints the following output...

123
123

However, I don't know why you would want to do that. It would be much simpler to use a single Scanner for your purposes. I called mine fin in the following snippet.

String next;
ArrayList<Integer> readIntegers = new ArrayList<>();
while (fin.hasNext()) {
    next = fin.next();
    while (next.equals("load") {
        next = fin.next();
        while (isInteger(next)) {
            readIntegers.Add(Integer.parseInt(next));
            next = fin.next();
        }
    }
}

Upvotes: 2

Related Questions