Monday, October 31, 2011

Getting number of lines in a file

The following code 'll return the number of lines in the file 'example.txt'
  1. public static int getNoOfLines(String filename){
  2.   File file = new File("example.txt");
  3.   if (!file.exists()){
  4.    System.out.println("File doesn't exist");
  5.    System.exit(0);
  6.   }
  7.   if (file.isDirectory()){
  8.    System.out.println("Expected file name but entered directory name");
  9.    System.exit(0);
  10.   }
  11.   int line = 0;
  12.   try {
  13.     LineNumberReader ln = new LineNumberReader(new FileReader(filename));                                                                        
  14.           while (ln.readLine() !null) {
  15.            line++;
  16.           }
  17.       } catch (IOException e) {
  18.        e.printStackTrace();
  19.       }
  20.   return line;  
  21.  }

No comments:

Post a Comment