Java: как определить, должна ли строка в текстовом файле быть пустой? - PullRequest
1 голос
/ 09 марта 2010

Я работаю над проектом, в котором мне нужно прочитать файл грамматики (разбивая его на структуру данных) с целью создания случайного «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

1 Ответ

1 голос
/ 09 марта 2010

Если я вас правильно понял, вы просто хотите определить внутри строки, пуста ли следующая строка?

Если это правда, то вот пример для начала:

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
...