Java Scanner with InputStream not working

2020-05-01 06:32发布

问题:

I am reading an InputStream (fis) from a source and on which I have to do some multiple search. I am using Scanner class and I instantiate it after every search. But it works only first time. Is there a way to reset the Scanner object? I have no control over the stream.

Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(
                fis, MIFConstants.ENCODING_UTF_8)));
        int count = 0;
        while (sc.hasNextLine()) {
            count++;
            sc.nextLine();
        }
        System.out.println(count);

        sc = new Scanner(new BufferedReader(new InputStreamReader(fis,
                MIFConstants.ENCODING_UTF_8)));
        count = 0;
        while (sc.hasNextLine()) {
            count++;
            sc.nextLine();
        }
        System.out.println(count);

The second print is returning zero. Any ideas about this?

回答1:

Create just one Scanner, and reuse it each time. The problem is happening because the BufferedReader *buffers* your input -- which means that it reads more than it needs and stores it up for later. When you create your second scanner, all the input has already been grabbed by the firstBufferedReader`, leaving nothing left to scan.



回答2:

The second print is returning zero.

Because you've already read the stream to EOS counting lines the first time. So when you do it again there are zero lines left to count, so you get zero.

Working as designed.