简体   繁体   English

如何检查文件中的空行,然后在Java中忽略它们?

[英]How do you check for blank lines in a file and then ignore them in Java?

I've seen similar questions asked about how to find a blank line. 我已经看到类似的问题,询问如何找到空白行。 I know how to find a blank line, but the sheer nature of finding it retrieves it and screws up the rest of your code. 我知道如何找到一个空行,但是找到它的纯粹本质是将其检索出来并弄乱了其余的代码。

Consider the following while loop: 考虑以下while循环:

while(file.hasNextLine()){
    if(file.nextLine.equals("")){
        continue;
    }
    String[] words = file.nextLine().split(" ");
    for(int i = 0; i < words.length; i++){
        System.out.print(words[i]);
    }
}

The idea here is to say, if there is a blank line, skip this iteration and move to the next line only extracting words. 这里的想法是,如果有空白行,则跳过此迭代,而仅提取单词移到下一行。 But just checking to see if the line is blank retrieves the next line (blank or not) and then retrieves the FOLLOWING line and stores it in words. 但是,仅检查行是否为空白即可检索下一行(是否为空白),然后检索跟随行并将其存储为单词。

What is the proper way to find blank lines without actually retrieving 'nextLine' to do so? 在不实际检索'nextLine'的情况下查找空白行的正确方法是什么?

Call file.nextLine() , but store it in a variable before checking it for emptiness. 调用file.nextLine() ,但在检查其是否为空之前将其存储在变量中。 That way you'll only call it once per iteration. 这样,您每次迭代只调用一次。

while(file.hasNextLine()){
    final String line = file.nextLine();
    if(line.isEmpty()){
        continue;
    }
    String[] words = line.split(" ");
    for(int i = 0; i < words.length; i++){
        System.out.print(words[i]);
    }
}

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

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