1

我正在做一个项目,我必须在其中读取语法文件(将其分解为我的数据结构),目标是能够生成随机的“DearJohnLetter”。

我的问题是,在读取 .txt 文件时,我不知道如何确定该文件是否应该是一个完全空白的行,这对程序是不利的。

这是文件的一部分的示例,我如何判断下一行是否应该是空行?(顺便说一句,我只是使用缓冲阅读器)谢谢!


<start>
I have to break up with you because <reason> . But let's still <disclaimer> .

<reason>
<dubious-excuse>
<dubious-excuse> , and also because <reason>

<dubious-excuse>
my <person> doesn't like you
I'm in love with <another>
I haven't told you this before but <harsh>
I didn't have the heart to tell you this when we were going out, but <harsh>
you never <romantic-with-me> with me any more
you don't <romantic> any more
my <someone> said you were bad news
4

1 回答 1

1

如果我理解正确,您只想在一行内确定下一行是否为空?

如果为真,那么这是一个启动示例:

package com.stackoverflow.q2405942;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {

    public static void main(String... args) throws IOException {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream("/test.txt")));
            for (String next, line = reader.readLine(); line != null; line = next) {
                next = reader.readLine();
                boolean nextIsBlank = next != null && next.isEmpty();
                System.out.println(line + " -- next line is blank: " + nextIsBlank);
            }
        } finally {
            if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
        }
    }

}

这将打印以下内容:

<start> -- next line is blank: false
I have to break up with you because <reason> . But let's still <disclaimer> . -- next line is blank: true
 -- next line is blank: false
<reason> -- next line is blank: false
<dubious-excuse> -- next line is blank: false
<dubious-excuse> , and also because <reason> -- next line is blank: true
 -- next line is blank: false
<dubious-excuse> -- next line is blank: false
my <person> doesn't like you -- next line is blank: false
I'm in love with <another> -- next line is blank: false
I haven't told you this before but <harsh> -- next line is blank: false
I didn't have the heart to tell you this when we were going out, but <harsh> -- next line is blank: false
you never <romantic-with-me> with me any more -- next line is blank: false
you don't <romantic> any more -- next line is blank: false
my <someone> said you were bad news -- next line is blank: false
于 2010-03-09T01:05:57.210 回答