Java - 扫描仪类 - 读取文本文件时跳过第一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21082139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:27:11  来源:igfitidea点击:

Java - Scanner Class - Skipping over the first line when reading a textfile

javafile-iojava.util.scanner

提问by pingOfDoom

When using a Scanner object to read from a textfile, I want it to skip over the very first line in the file. How would I do achieve this?

当使用 Scanner 对象从文本文件中读取时,我希望它跳过文件中的第一行。我将如何做到这一点?

采纳答案by Carsten Hoffmann

Just use file.nextLine()before your while loop. This will skip the first line, as explained in the JavaDoc.

只需file.nextLine()在 while 循环之前使用。这将跳过第一行,如JavaDoc中所述。

And a note about your naming. The Java language has widely accepted conventions. Class Names always start with an upper case letter, and variable names always start with a lower case letter (except constants, but don't worry about that now). Read more here.

以及关于您的命名的说明。Java 语言具有广泛接受的约定。类名总是以大写字母开头,变量名总是以小写字母开头(常量除外,但现在不用担心)。在这里阅读更多。

回答by Faiz

Add the below code before the whileloop to skip the first line.

while循环之前添加以下代码以跳过第一行。

if(file.hasNext()==true)
{
   file.nextLine();
}
else
{
    System.out.println("Error: File is empty");
    return null;
}