Java - 我想在读取文件时忽略空行

时间:2012-09-23 22:01:33

标签: java

这应该真的很简单,但无论出于何种原因......

String line;
String question = "";
Question qObj = new Question();
line = br.readLine(); //points to where i am in the file!
if (line == null){
    System.out.println("There was no question here. ");
    System.exit(1);
} else if (line.isEmpty() || line.trim().equals("") || line.trim().equals("\n")) {
     // do nothing, i don't want empty lines
} else {
    question = line;
}

while ((line = br.readLine())!= null){
    if (line.indexOf(LoadFromDb.ANSWER_BEGIN) == 0){
        dealWithAnswer(br, qObj);
        qObj.setQuestion(question);
        break;
    } else {
    if (!line.isEmpty()){
       question += "\n" + line.trim();
    }
}

如果上面的代码读取的第一行只是一个空行,那么它将空行添加到行对象,它不会跳过它。有什么想法吗?

3 个答案:

答案 0 :(得分:3)

关于我的回答*,这是我想象的那种解决方案:

} else if (line.isEmpty() || line.trim().equals("") || line.trim().equals("\n")) {
    do {
        line = br.readLine();
    }
    while(line.isEmpty() || line.trim().equals("") || line.trim().equals("\n"));
    question = line;
} else {
    question = line;
}

虽然我确信有更优雅的方式。

* Setting question to line doesn't appear to change what line is read later (if you're wanting the line to advance before it hits the while loop

答案 1 :(得分:2)

如果我理解正确的话,对我有用:

public class BlankLine
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new FileReader("blankline.txt"));
        String line;
        String question = "";
        line = br.readLine();
        if (line == null){
            System.out.println("There was no question here. ");
            System.exit(1);
        } else if (line.isEmpty() || line.trim().equals("") || line.trim().equals("\n")) {
            System.out.println("Skipped a blank line");
        } else {
            question = line;
            System.out.println("Question="+question);
        }

        // Update: added this to confirm we have skipped a line
        while ((line = br.readLine())!= null){
            System.out.println("Line:"+line);
        }
    }
}

输入:第一行为空白的文本文件,第二行带有“Hello World”文本

<强>输出

Skipped a blank line
Line:Hello World

答案 2 :(得分:2)

Java8

try(
    Stream<String> stream = Files.lines(
        Paths.get(INPUT_FILE_PATH), 
        Charset.defaultCharset())
){
    stream.map(line -> line.trim()) //Reading line
          .filter(line -> !line.isEmpty()) //Filtering empty lines
          .forEach(System.out::println); //Printing each line
} catch(Exception e) {  
    e.printStackTrace();            
}