您的位置:首页 > 其它

列出一个目录中所有文件及大小

2017-07-12 11:14 411 查看
package com.test.tree;

import java.io.File;

/**
* 列出一个目录中所有的文件和他们的大小
* @author wyl
*
*/
public class FileList {

public void list(File f){ //文件根目录,深度为0
list(f,0);
}

/**
*
* @param f
* @param depth 为了显示文件的层级形式
*/
public void list(File f, int depth){
printName(f, depth);
if(f.isDirectory()){
File[] files = f.listFiles();
for(File file:files){
list(file, depth+1);
}
}
}

/**
* 循环打印文件名及文件大小
* @param f
* @param depth
*/
private void printName(File f, int depth) {
// TODO Auto-generated method stub
String name = f.getName();
for(int i=0;i<depth;i++){ //缩进打印文件名
System.out.print("     ");
}
if(f.isDirectory()){
System.out.println("Dir: " + name);
}else{
System.out.println(f.getName() + "" + f.length());
}
}

public static void main(String[] args) {
FileList fileList = new FileList();
File file = new File("C:/");
fileList.list(file);
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: