【题目】
输入文件夹地址,读取文件夹所有文件并分析
需求:
- 判断文件夹是否为空
- 循环读取文件夹下所有文件夹的所有文件
- 分析所有文件
package analyze;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
public class FileOperation {
private int countbyte = 0;
private int countBlank = 0;
private int countTotalLine = 0;
private int totalLine = 0;
private int blank = 0;
private int bytes = 0;
private int files = 0;
private int curlevel; //层数记录
FileOperation(File dir,int level) throws Exception{
File[] listfiles = new File[dir.listFiles().length];
listfiles = dir.listFiles();
curlevel = level;
System.out.println(new String(new char[curlevel++]).replace("\0", " ") + "+" + dir.getName());
count(listfiles);
}
private void count(File[] listfiles) throws Exception { //对于文件夹的操作
for(int i = 0;i < listfiles.length;i++) {
if(listfiles[i].isFile()) {
countbyte = 0;
countBlank = 0;
countTotalLine = 0;
single(listfiles[i]);
totalLine += countTotalLine;
blank += countBlank;
bytes += countbyte;
files ++;
//统计单个文件
}
else if(listfiles[i].isDirectory()){
FileOperation fn = new FileOperation(listfiles[i],curlevel);
totalLine += fn.getTotalLine();
blank += fn.getBlank();
bytes += fn.getBytes();
files += fn.getFiles();
}
}
}
private void single(File file) throws Exception { //单个文件分析
Reader reader = new FileReader(file);
BufferedReader in = new BufferedReader(reader);
String line = null;
while((line = in.readLine()) != null) {
line = line.trim();
if(line.isEmpty()) {
countBlank++;
}
countbyte += line.getBytes().length;
countTotalLine++;
}
in.close();
System.out.print(new String(new char[curlevel]).replace("\0", " "));
System.out.printf("-%-30s Toatal:%6d,Blank:%6d,%10d Bytes\n",file.getName(),countTotalLine,countBlank,countbyte);
}
public int getTotalLine() {
return totalLine;
}
public int getBlank() {
return blank;
}
public int getBytes() {
return bytes;
}
public int getFiles() {
return files;
}
}
输出: