统计本地磁盘中某个目录下的所有文件数和总行数:
题目要求:传入如"D:\workspace" 这样的一个目录,
1.依次输出每个文件总行数,空白行数,实际行数
2.如果是目录也输出
3.输出总文件数,总行数,空白行数,实际行数
结果示例:输入:D:\workspace
结果:
D:\workspace
xxxx.java 总共13行 空白行3行 实际行10行
......
......
D:\workspace:总共1342 files, 87822 lines
在javaeye上找到的一个练习,怎么提高性能???
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class SourceCount {
private static int actCount = 0;
private static int spaceAllCount = 0;
private static int fileCount = 0;
public static void countLine(File file) throws Exception {
if (file.isFile()) {
fileCount++;
System.out.print(file.getName() + ":");
BufferedReader bf = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
String str;
int reallyCount = 0;
int spaceCount = 0;
while ((str = bf.readLine()) != null) {
if (str.trim().equals("")) {
spaceCount++;
} else
reallyCount++;
}
spaceAllCount = spaceAllCount + spaceCount;
actCount = actCount + reallyCount;
System.out.print(reallyCount + " lines" + "空格行数为:" + spaceCount
+ "总行数:" + (reallyCount + spaceCount));
System.out.println();
} else {
System.out.println(file);
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
countLine(files[i]);
}
}
}
public static void count(String dir) throws Exception {
File file = new File(dir);
countLine(file);
System.out.println("dir:" + file + " " + fileCount + " files,"
+ "实际行:"+actCount + " lines"+ "空白行:"+spaceAllCount+" lines"+" 共"+(spaceAllCount+actCount)+" lines");
}
public static void main(String[] args) throws Exception {
if(args.length()!=0){ String str = args[0]; }else{ String str = String dir = "F:/workspace/javaTest/src"; }
count(dir);
}
}