2

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

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();
    }
}

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

4

3 回答 3

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

于 2012-09-23T22:32:18.537 回答
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
于 2012-09-23T22:12:19.783 回答
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();            
}   
于 2016-01-13T06:03:57.233 回答