带有InputStream的Java Scanner无法正常工作 [英] Java Scanner with InputStream not working

查看:146
本文介绍了带有InputStream的Java Scanner无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从源读取一个InputStream(fis),我必须在其上进行多次搜索。我正在使用Scanner类,并在每次搜索后实例化它。但它只是第一次工作。有没有办法重置扫描仪对象?我无法控制流。

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?

推荐答案


第二次打印返回零。

The second print is returning zero.

因为你已经第一次读到EOS计数行的流。因此,当你再次这样做时,剩下的零线数,所以你得零。

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.

按设计工作。

这篇关于带有InputStream的Java Scanner无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆