Utility : Count the number of source code lines in text file   #


/** * This snippet shows how to count the lines in a text file (or multiple files depending on the command line) * Written by WolfCoder (2007) */ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * This snippet shows how to count the lines in a text file (or multiple files depending on the command line) Written by * WolfCoder (2007). */ public class LineCounter { // Data public static BufferedReader fileStream; // Text file reader string public static long totalLines; // Total lines of all the text files public static long tempLines; // Total lines of the current text file public static String textLine; // String of a text line // Opens a text file public static void openFile(String file) { try { // Try opening the file fileStream = new BufferedReader(new FileReader(file)); } catch (IOException e) { // Error System.out.println(file + " failed to open."); } } // Closes the text file public static void closeFile(String file) { try { // Try closing the file fileStream.close(); } catch (IOException e) { // Error System.out.println(file + " failed to close."); } } // Program entry public static void main(String[] args) { // Checks for no arguments if (args.length == 0) { // Prompt the user and exit System.out.println("Please supply the file name(s) of the text files to be line-counted."); return; } // Reset total lines totalLines = 0; // Opens each file and counts the lines for (int i = 0; i < args.length; i++) { // Open the file openFile(args[i]); // Reset temporary lines tempLines = 0; // Read all the lines that are possible while (true) { try { // Try to read the line textLine = fileStream.readLine(); } catch (IOException e) { // Error System.out.println("Line " + (tempLines + 1) + " failed to read in " + args[i]); } // Is it the end? if (textLine == null) break; // Yes. Now exit loop. // Not the end, count this line tempLines++; } // Lines read, report System.out.println(args[i] + " has " + tempLines + " lines."); // Tally up totalLines += tempLines; // Close the file closeFile(args[i]); } // Report total lines and exit System.out.println("Total lines: " + totalLines); } }

Loading Please Wait...