Tuesday, 4 August 2015

Getting number of lines in a file Using Java

The following code 'll return the number of lines in the file 'example.txt'

    public static int getNoOfLines(String filename){

      File file = new File("example.txt");
      if (!file.exists()){
       System.out.println("File doesn't exist");
       System.exit(0);
      }

      if (file.isDirectory()){
       System.out.println("Expected file name but entered directory name");
       System.exit(0);
      }

      int line = 0;
      try {
        LineNumberReader ln = new LineNumberReader(new FileReader(filename));                                                                      
              while (ln.readLine() != null) {
               line++;
              }
          } catch (IOException e) {
           e.printStackTrace();
          }
      return line;
     }

No comments:

Post a Comment