import java.io.*; //实现打印某个目录的全部子文件名称(包括子目录)
import java.util.Scanner;
public class Test { //命令行参数需要提供一个目录参数
public static void main(String[] args) throws Exception {
if (args.length!=1) {
System.out.println("Usage: java FileExample directory");
System.exit(0);
}
new Test().printFile(new File(args[0]));
Scanner in = new Scanner(System.in);
String dir = "", filename = "";
System.out.println("输入目录名:");
dir = in.next();
System.out.println("输入文件名:");
filename = in.next();
Test t = new Test();
File f = new File(dir);
int i = 0;
if( (i = t.find(f, filename)) == 0 ){
System.out.println("该目录下没有此文件。");
}else{
System.out.println("共找到" + i + "个文件。");
}
System.out.println(dir + " 目录下,文件总大小:" + t.totalSize(dir));
}
public void printFile(File f) throws Exception {
if (!f.isDirectory()) {
System.out.println("FileExample only accept directory parameter.");
System.exit(0);
}
System.out.println(f.getCanonicalPath()); //输出规范的相对对路径
File[] children = f.listFiles(); //得到目录的子文件(包括子目录)
for(int i=0;i<children.length;i++) {
if (children[i].isDirectory()) { //如果是子目录,则递归
this.printFile(children[i]);
}
else {
System.out.println(children[i].getCanonicalPath());
}
}
}
//搜索遍历某个目录,判断是否包含某文件
/**
*
* @param f
* @param filename
* @return
* @throws Exception
*/
public int find(File f, String filename) throws Exception{
int sum = 0;
if( !f.isDirectory() ){ //给的不是目录文件
if(f.getName() == null ? filename==null : f.getName().equals(filename)){//如果同名
System.out.println( f.getCanonicalPath() );
sum++;
return sum;
}
System.out.println( f.getName() + " is not a Directory." );
return sum;
}
File[] children = f.listFiles(); //得到目录下所有文件
for(int i=0; i<children.length; i++){ //遍历子目录
if( !children[i].isDirectory() ){ //如果不是目录文件
if(children[i].getName() == null ? filename == null : children[i].getName().equals(filename)){
System.out.println(children[i].getCanonicalPath());//同名输出目录的相对路径
sum++;
}
}
else{ //如果是目录,递归
sum += this.find(children[i], filename);
}
}
return sum;
}
//返回该目录的所有的文件大小之和
public long totalSize(String dir) {
long size = 0;
File f = new File(dir);
if( !f.isDirectory() ){//如果不是一个目录
size += f.getUsableSpace();
}
else{//如果是一个目录
File[] children = f.listFiles(); //得到目录下所有文件
for(int i=0; i<children.length; i++){
if( !children[i].isDirectory() ){//如果不是一个目录文件
size += children[i].getUsableSpace();
}
else{//如果是一个目录,递归
totalSize( children[i].getName() );
}
}
}
return size;
}
}