重置.nextLine()扫描程序

对于Java来说,我是业余爱好者,所以请原谅我的问题,如果它看起来很愚蠢:-P我有以下代码,用于计算文件中的行数:

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

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

(相反,我不得不使用另一台扫描仪用于其他目的,对我而言,这似乎不如它应该优雅。)

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

谢谢

CJ

这是不可能的。

不包括它的原因是它支持的各种输入类型。 一个例子是流。 它们在传递后不会存储结果,因此它们不支持重置。

所以优雅的方法是创建一个新的Scanner 。 如果为其提供了许多自定义设置,请创建工厂方法。

您必须重新声明Scanner 。 当您调用nextLine() ,该行将从缓冲区中删除,并从Scanner有效地丢弃。

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

 Scanner scanNumOfLines = new Scanner(myFile); 

Scanner对象中没有“计数器”。 相反,我认为它更像传送带。 皮带不知道或关心它的内容。 当它上面还有物品时,它会一直向你吐出东西。 一旦你拿走它们,它们就会永远消失。

我意识到这已经得到了回答,但是如果我正在查找这些东西,我肯定其他人也是,所以我想我会为解决这个问题做出贡献:因为我的问题需要我阅读文件基于用户输入的次数,我的测试类有一个读取文件的扫描器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 scanList = new ArrayList(); 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)); } } 
 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()); } 

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