有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

语法Java:如何判断文本文件中的一行是否应该为空?

我正在做一个项目,我必须读入一个语法文件(将它分解成我的数据结构),目标是能够生成一个随机的“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. # 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