如何使用Scanner检查线路末端?

我搜索过类似的问题,但都没有帮助。

考虑一个文件:

你好你好吗?
当时你在哪里?

我希望在每一行结束后进行一些操作。 如果我使用next()它不会告诉我何时到达第一行的末尾。

我也见过hasNextLine()但它只告诉我是否存在另一行。

考虑使用多个扫描仪,一个用于获取每一行,另一个用于在收到后扫描每一行。 我必须提出的唯一警告是,您必须确保在使用完毕后关闭内置扫描仪。 实际上,您需要在使用完毕后关闭所有扫描仪,尤其是内部扫描仪,因为它们可能会增加并浪费资源。

例如,

 Scanner fileScanner = new Scanner(myFile); while (fileScanner.hasNextLine()) { String line = fileScanner.nextLine(); Scanner lineScanner = new Scanner(line); while (lineScanner.hasNext()) { String token = lineScanner.next(); // do whatever needs to be done with token } lineScanner.close(); // you're at the end of the line here. Do what you have to do. } fileScanner.close(); 

您可以逐行扫描文本,并使用String.split()方法拆分标记中的每一行。 通过这种方式,您可以知道一行何时结束并且每行都有所有令牌:

 Scanner sc = new Scanner(input); while (sc.hasNextLine()){ String line = sc.nextLine(); if (line.isEmpty()) continue; // do whatever processing at the end of each line String[] tokens = line.split("\\s"); for (String token : tokens) { if (token.isEmpty()) continue; // do whatever processing for each token } } 

当我读到这篇文章时,不确定这是否相关或太晚。 我对Java比较新,但是当我遇到类似的问题时,这似乎对我有用。 我刚刚使用了DO-WHILE循环,其中文件结尾符号由一个简单的字符串表示。

 import java.util.ArrayList; import java.util.List; import java.util.Scanner;`enter code here` public class Main { public static void main(String[] args) { List name = new ArrayList<>(); Scanner input = new Scanner(System.in); String eof = ""; do { String in = input.nextLine(); name.add(in); eof = input.findInLine("//"); } while (eof == null); System.out.println(name); } } 

您可以使用扫描仪和您提到的方法:

  Scanner scanner = new Scanner(new File("your_file")); while(scanner.hasNextLine()){ String line = scanner.nextLine(); // do your things here }