简体   繁体   English

如何在读取文件时跳过空行(java)?

[英]How to skip an Empty line while reading a file (java)?

I am trying to read this file, and then put it into a List: 我正在尝试读取此文件,然后将其放入列表中:

23333
Manuel Oliveira
19

222222
Mário Santos
18

using Scanner. 使用扫描仪。 This is how I've done if Ignore the empty line between 19 and 222222. 如果忽略19和222222之间的空行,这就是我的工作方式。

public List<Aluno> lerFicheiro ( String nomeF) throws FileNotFoundException{
    List<Aluno> pauta = new LinkedList<Aluno>();
try{
    Scanner s = new Scanner ( new File ( nomeF));
    int cont = 0;
    String numero = null;
    String nome = null;;
    String nota;
    while ( s.hasNextLine())
    {
        if ( cont ==0)
        {
             numero = s.nextLine();
        }
        else
        {  
          if ( cont == 1) 
             nome = s.nextLine();
          else
          {   
              if ( cont == 2) 
              {
                  nota = s.nextLine();
                  cont =-1;
                  pauta.add( new Aluno(Integer.valueOf(numero), nome, nota)); 
              }
           }
        }
        cont++;
    }
    s.close();
}
catch ( FileNotFoundException e)
{
    System.out.println(e.getMessage());
}
return pauta;
}

But I've no idea how to still read it with the empty line. 但是我不知道如何仍然用空行读取它。 Thank you. 谢谢。

For a beginner, you have a good start of a rudimentary state machine there. 对于初学者,您在那里有一个基本的状态机的良好开端。 There are two ways you can think about the empty line: 您可以通过两种方式考虑空行:

  1. You're not interested in any empty line. 您对任何空行都不感兴趣。 So you just ignore them and don't change your cont . 因此,您只需忽略它们,而不更改您的cont
  2. You are specifically not interested in an empty line after the "nota". 您特别对“ nota”之后的空白行不感兴趣。 In this case, you should add this as a fourth state. 在这种情况下,您应该将此添加为第四状态。

The advantage of the first approach is that even if there is more than one empty line in the file, or an empty line after the name, it will be ignored. 第一种方法的优点是,即使文件中有多个空行或名称后有空行,也将忽略该行。 The second approach is better if other empty lines that don't come after "nota" are useful. 如果“ nota”之后没有出现的其他空行有用,则第二种方法更好。

I think it would be more elegant to read the line, and then decide what to do with it based on the cont . 我认为阅读该行,然后根据cont决定如何处理它会更优雅。 So for the first approach (ignore any empty line): 因此,对于第一种方法(忽略任何空行):

while ( s.hasNextLine()){

    // First read
    String theLine = s.nextLine();

    // Ignore it if it's empty. That is, only do something if
    // the line is not empty

    if ( ! theLine.isEmpty() ) {

        if ( cont == 0){
             numero = theLine; // You use the line you have read
        }else if ( cont == 1) {
             nome = theLine;
        }else {
             nota = theLine;
             cont =-1;
             pauta.add( new Aluno(Integer.valueOf(numero), nome, nota)); 
        }

        cont++;
    }

}

When you read an empty line, the state ( cont ) is not changed. 读取空行时,状态( cont )不会更改。 So it's as if that line never existed. 好像那条线根本不存在。

Note that it would be nicer to use constants instead of just 0 , 1 , 2 , so that they will be meaningful. 请注意,这将是更好的使用常量,而不是仅仅012 ,这样他们才会有意义。

Also note the way to properly write if...else if...else . 还要注意正确编写if...else if...else You don't need to put them in curly braces all the time. 您无需一直将它们放在花括号中。

You could set delimiter to regex representing one or more line separators like (\\r?\\n)+ (or since Java 8 \\R+ ) and simply use next() method to read lines. 您可以将定界符设置为表示一个或多个行分隔符的正则表达式,例如(\\r?\\n)+ (或从Java 8 \\R+ ),而只需使用next()方法即可读取行。

BTW: you should not be placing close() inside try block but in finally block. 顺便说一句:您不应该将close()放置在try块中,而应该放置在finally块中。 Or better use try-with-resources. 或更好地使用try-with-resources。

So if you are sure that file will always contain tokens build from 3 lines then your method can look like (I changed return type to List<String> for simplicity, but you should be able to change it back quite easily) 因此,如果您确定文件将始终包含从3行构建的令牌,则您的方法应类似于(为简单起见,我将返回类型更改为List<String> ,但您应该能够很容易地将其更改回)

public static List<String> lerFicheiro(String nomeF)
        throws FileNotFoundException {

    List<String> pauta = new LinkedList<>();
    try (Scanner s = new Scanner(new File(nomeF))){
        s.useDelimiter("\\R+");

        while (s.hasNext()) {
            //since delimiter is line separator `next` will read lines
            String numero = s.next();
            String nome = s.next();
            String nota = s.next();
            pauta.add(numero + ":" + nome + ":" + nota);
        }
    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    }
    return pauta;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM