Java I/O How to - Display first and last lines of Text File








Question

We would like to know how to display first and last lines of Text File.

Answer

import java.io.BufferedReader;
import java.io.FileReader;
/*from w ww . java2  s .  c o m*/
public class Main {
  
  public static void main(String[] args) throws Exception {
    String first, last=null, line;
    BufferedReader in = new BufferedReader(new FileReader(args[0]));
    first = in.readLine();
    while ((line = in.readLine()) != null) {
      if (line != null) {
        last = line;
      }
    }
    System.out.println(first + "\n" + last);
    in.close();
  }
}