This is a lines-counter program. To count the number of lines in a file, the file name must be entered when you run the program from the command prompt window. In this program, you learn FileReader class to read the content of the file one by one character. Each line of text in the file has its new line character ('\n'). So you can base on this character to count the number of lines in the file.
LinesCounter source code:
1 import java.io.*;
class LinesCounter{
public static void main(String[] args){
2 if(!args[0].equals(""))
System.out.println("Number of lines:"+countLines(args[0]));
else{
System.out.println("Please input the file name when you run the program");
System.out.println("e.g. java LinesCounter myfile.txt)");
}
}
3 public static int countLines(String filename){
int numlines=0;
int ch=0;
char c=' ';
try{
4 FileReader fr=new FileReader(filename);
while ((ch=fr.read())!=-1){
c=(char)ch;
if(c=='\n') numlines++;
}
5 fr.close();
} catch(IOException ie){System.out.println("IO problem!");}
6 return numlines;
}
}
Program Output:
Code Explanation:
1 Introduce io package to the program. The io package contains a lot of classes that can be used to manipulate file stream.
2 Check whether the parameter args has a value. The args is an array of string. You can enter many values when the java command is used to run the program in the command prompt window. In this program, only one value (the file name) is needed. args[0] stores this value. If you enter another value, the value will be stored in args[1].
3 The countLines method contains code to read content of the file and count the number of lines in the file. This method is declared with static keyword. A method declared with static keyword can be invoked without an object.
4 Create FileReader object fr to read each character in the file.
5 Close the file.
6 Return the number of lines counted.
Another version of the lines-counter program in which the static keyword is not used when defining the countLines(String filename) method is shown below. The LinesCounter object lc needed to call this method from the main method.
1 import java.io.*;
class LinesCounter{
public static void main(String[] args){
LinesCounter lc=new LinesCounter();//Create lc object
2 if(!args[0].equals(""))
System.out.println("Number of lines:"+countLines(args[0]));
else{
System.out.println("Please input the file name when you run the program");
System.out.println("e.g. java LinesCounter myfile.txt)");
}
}
3 public int countLines(String filename){
int numlines=0;
int ch=0;
char c=' ';
try{
4 FileReader fr=new FileReader(filename);
while ((ch=fr.read())!=-1){
c=(char)ch;
if(c=='\n') numlines++;
}
5 fr.close();
} catch(IOException ie){System.out.println("IO problem!");}
6 return numlines;
}
}
No comments:
Post a Comment