简体   繁体   English

如何在Java中使用扫描仪扫描特定行?

[英]How to scan specific line using scanner in java?

When using Scanner utility in Java, how to scan a specific line or scan a line twice? 在Java中使用扫描仪实用程序时,如何扫描特定行或扫描两次? Like when I using scanner.nextLine(), how do I go back to this line again? 就像我使用scanner.nextLine()一样,如何再次回到该行? Or how to read any line twice? 或者如何两次读取任何行? Is that possible? 那可能吗?

Unfortunatly no 不幸的是没有

Scanner was created to read streams and they don't "store" the information they read. 创建扫描程序以读取流,并且它们不“存储”所读取的信息。 Meaning should your source be reading some transmission over the internet it can't go back and read it again for example. 这意味着您的源应该正在通过互联网读取某些传输,例如,它不能返回并再次读取。 Scanner handles files in a similar way to those internet transmissions by creating an input stream from the file and handling all the fancy encodings and all that for you. 扫描程序通过从文件创建输入流并处理所有精美的编码以及为您完成的所有操作,以与那些Internet传输类似的方式处理文件

If you want to read a line from a file again or hop back to another line your best option is to close the scanner, create a new scanner object and go all the way down again to the preferred line. 如果要再次从文件中读取一行或跳回另一行,最好的选择是关闭扫描仪,创建一个新的扫描仪对象,然后再次向下转到首选行。

Quick example: 快速示例:

Let's say we're looking for a name that's above the name we ask it to search for in a file containing names: 假设我们正在寻找一个名称,该名称高于我们要求它在包含名称的文件中搜索的名称:

One approach would be to loop through the file in a while loop, reading a line(name) and seeing if it matches our name, if it does we store the line we read it from, close the scanner, create a new scanner object and start the looping process again, this time stopping when we reached the line before the name we were searching for and bam! 一种方法是在while循环中循环浏览文件,读取行(名称)并查看其是否与我们的名称匹配,如果确实存储了我们从中读取的行,则关闭扫描仪,创建一个新的扫描仪对象,然后再次开始循环过程,这次是当我们到达要搜索的名称之前的行并停止时停止!

Another (and better approach in my opinion) would be to store all the information we read from scanner (in our example names) in a list of some sort (in our example an arraylist would be perfect). 另一种(在我看来,更好的办法)将存储所有我们在读取扫描仪(在我们的例子名称)的信息列表某种(在我们的例子一个ArrayList的将是完美的)。 We can then use that list to read a line twice, read the 5th line (5th element in the list) or go back to a previous line 然后,我们可以使用该列表两次读取一行,读取第五行(列表中的第五元素)或返回上一行

Hope this helps and if you need some code feel free to ask :) 希望这会有所帮助,如果您需要一些代码,请随时询问:)

Scanner wasn't built to do that - Plus, the Scanner class does not keep any history of any lines at all 并非为创建Scanner而设计的-此外,Scanner类根本不保留任何行的任何历史记录

.nextLine() would just give you the whole line (the first one) and .next() would just give you the first word. .nextLine()将只给你整条生产线(第一个)和的.next()将只是给你的第一个字。 It does not store any lines/words/characters. 它不存储任何行/单词/字符。

我认为您不能使用扫描仪本身来执行此操作,但是可以使用基础BufferedInputStream mark()reset()方法返回到先前读取的位置。

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

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