繁体   English   中英

带有InputStream的Java扫描仪不起作用

[英]Java Scanner with InputStream not working

我正在从源中读取InputStream(fis),并且必须对其进行多次搜索。 我正在使用Scanner类,并在每次搜索后实例化它。 但这仅是第一次。 有没有一种方法可以重置扫描仪对象? 我无法控制流。

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);

第二个打印返回零。 有什么想法吗?

仅创建一个Scanner ,然后每次重复使用。 发生问题是因为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 first *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 first 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 first ,不留任何内容进行扫描。

第二个打印返回零。

因为您已经第一次将流读取到EOS计数行。 因此,当您再次执行此操作时,剩下的行数仍为零,因此您将获得零。

按设计工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM