繁体   English   中英

Java扫描程序不会读取文件末尾的空行

[英]Java scanner will not read empty line at end of file

我正在写一个读取数据文件的文件解析器

BREAK ;
     FI
 REPEAT
  PRINT "bye all"
.
//empty line

并解析字符,空格,(、;等)并将每个项目存储在Arraylist中。我可以读取开头和正文的空行,但不能读取结尾的空行。

Scanner fileInput = new Scanner(new File(path));
int count = 0;
while (fileInput.hasNextLine()) {
    count++;
    line.clear();
    System.out.println("hasNext");
    //line holds entire line since scanner skips spaces
    String a = fileInput.nextLine();
    System.out.println("a is String" + a);
    int i = 0;
    String str = ""; // used to store single word and spaces
    boolean stop = false;
    if (a.isEmpty()) {
        line.add("EoLn");
        System.out.println("line " + count + " EOL");
    }
}

全文https://gist.github.com/dcf7a215f3582bae962a.git[1]

默认情况下, Scanner使用空格作为分隔符。 你可以做

fileInput.useDelimiter(System.getProperty("line.separator"));

由于行中没有任何内容可以解析空格分隔符,因此Scanner可能认为该行无关紧要。 您的代码看起来不错。 因为您只用它读取行,所以我将切换到BufferedReader.readLine().

暂无
暂无

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

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