带有InputStream的Java Scanner无法正常工作

我正在从源读取一个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计数行的流。 因此,当你再次这样做时,剩下的零行数,所以你得零。

按设计工作。