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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2292917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:45:44  来源:igfitidea点击:

How to detect first and last line during reader.readLine()?

javafile

提问by Arav

I am reading each line of the file in the below way

我正在以下面的方式阅读文件的每一行

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

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


}

I want to do some validation in the first line and last line alone. Is there any way to check if it's a first line and last line inside the while loop

我想单独在第一行和最后一行做一些验证。有没有办法检查它是否是while循环内的第一行和最后一行

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

    if(firstlineoffile) {
    }

    else if (lastlineoffile) {
    }

    else
    {
    }

}

采纳答案by BalusC

Cool question. I played a bit round it and here's an SSCCE, just copy'n'paste'n'run it.

很酷的问题。我玩了一会儿,这是一个SSCCE,只需复制'n'paste'n'run它。

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();
    }

}

Output:

输出:

first line: line 1
normal line: line 2
normal line: line 3
normal line: line 4
last line: line 5

I however question the readability and interpretability by starters... ;)

然而,我质疑初学者的可读性和可解释性...... ;)

回答by Upgradingdave

if you add a count, and rearrange your code a little, this should work (I haven't tested this so there may be syntax errros):

如果你添加一个计数,并稍微重新排列你的代码,这应该可以工作(我没有测试过这个,所以可能会有语法错误):

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++;
}

回答by Kylar

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();
}

回答by Chinmay Kanchi

Someone might well come up with a more elegant solution than this, but here we go:

有人可能会想出比这更优雅的解决方案,但我们继续:

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);

I haven't tested this, so there might be minor errors. I haven't sorted out exception handling in this code. readLine(), mark()and reset()throw IOExceptionand mark()can also throw IllegalArgumentException

我没有测试过这个,所以可能会有小错误。我还没有整理这段代码中的异常处理。readLine(),mark()reset()throwIOExceptionmark()可以扔IllegalArgumentException

回答by Vijay

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();
            }
        }
    }