This program is written primarily to determine whether it is a folder, and whether it is a Java file. When programming attention to the use of member variables and local variables, I started by using local variables to recursion, but the value is 0, because the value is reset in recursion. I didn't notice the name when I took it.
countlist2.java//to count the number of Java lines of code
Import Java.io.BufferedReader;
Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileReader;
Import java.io.IOException;
public class CountList2 {
int countsum;//lines of code
public int getFile (String filePath) throws FileNotFoundException {
try {
File File = new file (FilePath);
if (File.isdirectory ()) {//Determine if it is a folder
file[] Codefiles = File.listfiles ();
int s = codefiles.length;
for (int i = 0; i < s; i++) {
GetFile (Codefiles[i].getpath ());
}
} else {
if (File.getname (). EndsWith (". Java")) {//Determine if it is a Java file
System.out.println (File.getname ());//output Java file name
Countsum + = filelist (file);
}
}
catch (FileNotFoundException e4) {
System.out.println ("Erroe1");
E4.printstacktrace ();
catch (@SuppressWarnings ("hiding") IOException E1) {
System.out.println ("Erroe2");
E1.printstacktrace ();
}
return countsum;
}
public int filelist (file file) {
int countsum = 0;//Line of code
int blanksum = 0;//number of blank lines
int commentsum = 0;//comment number of lines
BufferedReader br = null;
try {
br = new BufferedReader (new FileReader (file));
String line = null;
while (line = Br.readline ())!= null) {
line = Line.trim ();
if (Line.matches ("^[\\s&&[^\\n]]*$")) {
blanksum++;
else if (Line.startswith ("//)") {
commentsum++;
else if (Line.startswith ("/*")) {
commentsum++;
else if (Line.startswith ("*")) {
commentsum++;
else if (Line.endswith ("* *")) {
commentsum++;
} else {
countsum++;
}
}
Br.close ();
catch (Exception e) {
System.out.println ("Erroe3");
E.printstacktrace ();
}
return countsum;
}
}
countlist1.java//used to test
Import java.io.FileNotFoundException;
public class CountList1 {
public static void Main (string[] args) throws FileNotFoundException {
String FilePath = "E:\\nbtserver";
COUNTLIST2 fn = new CountList2 ();
int Countsum1=fn.getfile (FilePath);
System.out.println ("countsum:" + countSum1);
}
}