import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; // Reads all the lines of a file and prints out the count public class CountFileLines { public static void main(String[] args) { Scanner sc = null; try { // Ask the user for a file name Scanner scanner = new Scanner(System.in); System.out.println("Enter a file name: "); String fileName = scanner.nextLine(); // Open that file sc = new Scanner(new File(fileName)); int count = 0; // Read one line of the file at a time and print it out while ( sc.hasNextLine() ) { String st = sc.nextLine(); count++; } // Print out the number of lines in the file System.out.println("Count: "+count); } catch (FileNotFoundException e) { System.out.println("Did not find input file: "+e); } finally { if (sc != null) sc.close(); } } }