如何在reader.readLine()期间检测第一行和最后一行?

16

我正在以以下方式逐行读取文件:

BufferedReader in = new BufferedReader(new FileReader(inFile));

while (null != (line = in.readLine())) {


}

我想在第一行和最后一行进行一些验证。有没有办法在while循环中检查是否为第一行或最后一行。

while (null != (line = in.readLine())) {    

    if(firstlineoffile) {
    }

    else if (lastlineoffile) {
    }

    else
    {
    }

}

将您的代码缩进4个空格以格式化它。我已经为您在此帖子中修复了它。 - Chinmay Kanchi
5个回答

16

很棒的问题。我稍微试了一下,并提供了一个SSCCE,只需复制、粘贴和运行即可。

package com.stackoverflow.q2292917;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

public class Test {

    public static void main(String... args) throws IOException {
        // Create test file.
        File file = new File("/test.txt");
        PrintWriter writer = new PrintWriter(file);
        writer.println("line 1");
        writer.println("line 2");
        writer.println("line 3");
        writer.println("line 4");
        writer.println("line 5");
        writer.close();

        // Read test file.
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String next, line = reader.readLine();
            for (boolean first = true, last = (line == null); !last; first = false, line = next) {
                last = ((next = reader.readLine()) == null);

                if (first) {
                    System.out.println("first line: " + line);
                } else if (last) {
                    System.out.println("last line: " + line);
                } else {
                    System.out.println("normal line: " + line);
                }
            }
        } finally {
            if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
        }

        // Delete test file.
        file.delete();
    }

}

输出:

第一行:line 1
普通行:line 2
普通行:line 3
普通行:line 4
最后一行:line 5

然而,我质疑新手的可读性和解释能力... ;)


1
对于单行文件,该方法会报告“第一行”,这并不是错误的,但有时您需要知道它是否是最后一行。为此,我建议在first && last == true的情况下添加第四个状态“single”。 - Udo
一个简单直接的解决方案。我已经寻找这种解决方案三个小时了,终于找到了! - Brooklyn99

0
public class Vomitfirstline {

    public static void main(String[] args) {

        BufferedReader br = null;

        try {

            String sCurrentLine;

            br = new BufferedReader(new FileReader("Path"));
             br.readLine();

            {


                while ((sCurrentLine = br.readLine()) != null)
        System.out.println(sCurrentLine);

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

0
如果你添加一个计数器,并稍微调整一下代码,这个应该可以工作(我没有测试过,所以可能会有语法错误):
int count = 0;
String line = in.readLine();
while (line!=null) {
  String currLine = line;
  if(count==0){
     //currLine is the first line
  }

  line = in.readLine();
  if(line==null){
     //currLine is the last line
  }

  if(count>0 && line!=null){
     //do something with lines in between
     System.out.println(currLine);
  }
  count++;
}

1
如果 line==null,那么你已经超过了最后一行。你总是需要向前查看,如果 nextLine==null,那么你就到了最后一行。 - Kylar
1
或者你可以将其重构为do-while循环,这将消除循环外的readLine()。此外,如果line==null,则“上一个”行是最后一行,而不是当前行。 - Chinmay Kanchi

0
String currentLine = in.readLine();
String nextLine = in.readLine();
boolean hasStarted = false;
while(null != currentLine){
    if(!hasStarted){
        //first line.
        hasStarted = true;
    }
    //all your processing here.
    if(null == nextLine){
        //last line, cause there's nothing else coming up
    }
    currentLine = nextLine;
    nextLine = in.readLine();
}

-1

可能会有人想出比这更优雅的解决方案,但是我们来试试这个:

boolean isFirstLine = true;
do{
      String line = in.readLine();
      if(isFirstLine){
         //this is the first line
         isFirstLine = false; 
      }
      else if(line==null){ //previous line was the last line
         in.reset();
         line = in.readLine();
         //do last line specific stuff
         break;
      }
      else {
          //do stuff for lines in between
      }
      in.mark(100);

}while (line!=null);

我还没有测试过这个,所以可能会有一些小错误。我还没有在这段代码中解决异常处理问题。readLine()mark()reset()会抛出IOException异常,而mark()也可能会抛出IllegalArgumentException异常。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接