文件大小

import java.io.File;

public class FileSizeTest {

	/* 
	* 计算文件夹的大小 
	*/ 
	public static void main(String[] args) { 

		File dir = getDir(); 
		float length = getDirLength(dir); 
		if (length == 0) { 
			System.out.println("此文件夹为空."); 
		} else if (length < 1024) { 
			System.out.println(length + " byte"); 
		} else if (length < 1024 * 1024) { 
			System.out.println(length / 1024 + " kb"); 
		} else if (length < 1024 * 1024 * 1024) { 
			System.out.println(length / (1024 * 1024) + " mb"); 
		} else { 
			System.out.println(length / (1024 * 1024 * 1024) + " Gb"); 
		} 
	} 

	public static float getDirLength(File dir) { 
		long length = 0; 
		File[] subFiles = dir.listFiles(); 
		for (File subFile : subFiles) { 
			if (subFile.isFile()) { 
				length += subFile.length(); 
			} else { 
				length += getDirLength(subFile); 
			} 
		} 
		return length; 
	}
	
	public static File getDir() { 
		while (true) { 
			String pathname = "D:/www"; 
			File dir = new File(pathname); 
			if (!dir.exists()) { 
				System.out.println("您输入的路径不存在,请重新输入."); 
			} else if (dir.isFile()) { 
				System.out.println("您输入的是一个文件路径,请输入一个文件夹路径."); 
			} else { 
				return dir; 
			} 
		} 
	}
}

你可能感兴趣的:(文件大小)