14

当谈到 Java 时,我是一个业余爱好者,所以如果它看起来很愚蠢,请原谅我的问题:-P 我有以下代码,旨在计算文件中的行数:

while (scanNumOfLines.hasNextLine())    
    {
    NumOfLines ++;
    scanNumOfLines.nextLine();
    }
    System.out.println("NumOfLines = "+NumOfLines);

所以它算不错,但我想将扫描仪重新用于其他目的,但 nextLine 已移动到文件的最后一行,我想将其重置回第一行。

(相反,为了其他目的,我不得不使用另一台扫描仪,在我看来,这似乎不如应有的优雅。)

我确定必须有一种扫描仪方法将计数器重置为零?

谢谢

CJ

4

5 回答 5

15

这是不可能做到的。

不包括它的原因是它支持的输入类型范围很广。一个例子是流。这些在传递后不存储结果,因此它们不支持重置。

所以优雅的方式是创建一个新的Scanner. 如果你给它很多自定义设置,创建一个工厂方法。

于 2012-12-21T14:01:59.347 回答
8

您将不得不重新声明Scanner. 当您调用nextLine()时,该行将从缓冲区中删除并有效地从Scanner.

所以,本质上,有一种方法可以做到这一点:它是构造函数。

Scanner scanNumOfLines = new Scanner(myFile);

对象中没有“计数器” Scanner。相反,它更像是一条传送带。皮带不知道也不关心上面有什么。它只是不停地向你吐东西,而上面还有东西。一旦你拿走它们,它们就会永远消失。

于 2012-12-21T14:00:15.720 回答
1

我意识到这已经得到了回答,但是如果我正在查找这些东西,我相信其他人也是如此,所以我想我会按照我解决这个问题的方式做出贡献:因为我的问题需要我阅读文件多次根据用户输入,我的测试类有一个 ArrayList 扫描仪读取文件,然后在不再需要时自行删除。我设置它的方式在 ArrayList 中永远不会超过 1 个扫描仪,但 ArrayList 在添加和删除对象时很有用。

public class TxtReader {
     private boolean PROGRAM_CONTINUES = true;
     private final int indexCount = 0;
     File newFile = new File("Reader Example.txt");
     ArrayList<Scanner> scanList = new ArrayList<Scanner>();

     public TxtReader(Scanner UserInput) throws FileNotFoundException {
         while(PROGRAM_CONTINUES) {
              if (UserInput.next().equalsIgnoreCase("end")) { 
          // some arbitrary way of concluding the while loop
                  PROGRAM_CONTINUES = false;
                  break;
              }
              scanList.add(new Scanner(newFile));
          // DO STUFF*********************************************
              while(scanList.get(indexCount).hasNext()) {
                 System.out.println(scanList.get(indexCount).nextLine());
             }
          //******************************************************
              scanList.get(indexCount).close(); 
          //always close a scanner after you're done using it
              scanList.remove(indexCount); // removes the now-unnecessary scanner 
              UserInput = new Scanner(System.in);
        }
    }
    public static void main(String[] args) throws FileNotFoundException {
        new TxtReader(new Scanner(System.in));
    }
}
于 2015-11-16T20:05:57.710 回答
0
File file = new File("StoreData.txt");

Scanner reader = new Scanner(new FileInputStream(file));
while (reader.hasNext()) {
        k++;
        reader.nextLine();
}
reader.close();
reader=null;    
//reset scanner         
reader=new Scanner(new FileInputStream(file));
while (reader.hasNext()) {
    System.out.println(reader.nextLine());              
}
于 2014-01-26T18:53:45.103 回答
-1

您可以使用RandomAccessFile并使用方法seek()回到第一行。

于 2012-12-21T14:00:54.373 回答