IO_File_案例_文件夹统计

版权声明: https://blog.csdn.net/weixin_40072979/article/details/82993685

1:首先来统计一下某个文件夹下的子孙级文件的名称 (递归算法)

package com.jianshun;

import java.io.File;
/**
 * 递归:方法自己调用自己
 * 打印子孙目录和文件名称
 * @author fanfan
 *
 */
public class DirDemo04 {
	public static void main(String[] args) {
		File src = new File("F:/workspace/IO_study01");
		printName(src,0);
	}
	
	//递归打印子孙级目录和文件名称
	public static void printName(File src,int deep){
		//控制前面层次
		for(int i=0;i<deep;i++){
			System.out.print("-");
		}
		System.out.println(src.getName());
		if(null == src || !src.exists()){//递归头
			return;
		}else if(src.isDirectory()){
			for(File s : src.listFiles()){
				printName(s,deep+1);
			}
		}
	}
}

2:统计文件的大小(以面向对象的思想来写)

package com.jianshun;

import java.io.File;

public class DirCount {
	//文件大小
	private long len;
	//文件夹数量
	private int dirSize;
	//文件数量
	private int fileSize;
	//文件夹
	private String path;
	//源
	private File src;
	
	
	public int getDirSize() {
		return dirSize;
	}

	public int getFileSize() {
		return fileSize;
	}

	public long getLen() {
		return len;
	}

	public DirCount(String path){
		this.path = path;
		this.src = new File(path);
		count(this.src);
	}
	
	public static void main(String[] args) {
		DirCount dir = new DirCount("F:/workspace/IO_study01");
		System.out.println(dir.getLen());
	}
	
	//统计大小
	public  void count(File src){ 
		//获取大小
		if(null != src && src.exists()){
			if(src.isFile()){
				len += src.length();
				this.fileSize++;
			}else{
				this.dirSize++;
				for(File s : src.listFiles()){
					count(s);
				}
			}
		}
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_40072979/article/details/82993685