【发布时间】:2016-04-29 05:35:07
【问题描述】:
我认为我在做一些非常愚蠢的事情,但我是 Java 新手,所以请耐心等待。我正在使用 FileReader 和 Scanner 来读取 .txt 文件的行。抓取每一行后,我提取一些信息,然后移动该行。这是我的简化方法的样子:
Reader fileReader = new FileReader("test.txt");
Scanner scanner = new Scanner(fileReader);
public static textList(Scanner scanner){
while (scanner.hasNextLine()){
scanner.nextLine();
while(scanner.hasNext()){
// Extract information from each line and do some stuff with it
// using scanner.next();
}
}
}
// scanner is closed in the same method that creates it and the FileReader.
我的问题是,如果我将 scanner.nextLine() 留在原处,我将始终跳过 .txt 文件的第一行,但如果我将其移动到 while( scanner.hasNextLine()) 的末尾,我会得到一个“当扫描仪到达 .txt 文件的末尾时,不存在这样的行”异常。
任何帮助和指导将不胜感激!
谢谢
【问题讨论】:
-
为什么不使用 -
while (scanner.hasNextLine()){ String s = scanner.nextLine() ... Other code here? -
是否可以从 s 中提取不同的标记?我澄清一下,每行有5个数据串,我需要把这些数据位分开
-
nextLine()使用并返回一行文本。next()跳过空格,消耗并返回一个令牌。因此,您调用nextLine()所使用的任何文本都将被丢弃,因为您不使用返回值。 -
@flexcookie - 是的,您可以在空格上拆分输入行以获取令牌
-
是的。
s = scanner.nextLine()会将下一行的内容分配给s,因为nextLine()返回一个字符串。
标签: java methods java.util.scanner