Android 获取文件&文件夹的大小

4,129 阅读1分钟

一、获取文件的大小

  1. File的length()方法,返回long值,如果该File是文件夹就不能获得准确大小
  2. FileInputStream的available()方法,返回int值,这就导致操作大文件时候,后者可能无法获得正确的大小。
  3. FileChannel 位于java.nio包,能够在流式操作下获取文件准确大小,示例如下:
public static void main(String[] args) {
	FileChannel fc= null;
	try {
		File f= new File("D:\\CentOS-6.5-x86_64-bin-DVD1.iso");
		if (f.exists() && f.isFile()){
			FileInputStream fis= new FileInputStream(f);
			fc= fis.getChannel();
			logger.info(fc.size());
		}else{
			logger.info("file doesn't exist or is not a file");
		}
	} catch (FileNotFoundException e) {
		logger.error(e);
	} catch (IOException e) {
		logger.error(e);
	} finally {
		if (null!=fc)){
			try{
				fc.close();
			}catch(IOException e){
				logger.error(e);
			}
		} 
	}
}

参考: blog.csdn.net/bzlj2912009…

二、获取文件夹大小

private long getFolderSize(File file) {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) size = size + getFolderSize(fileList[i]);
                else size = size + fileList[i].length();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

其余操作,获取SD卡大小空间

blog.csdn.net/qq_16628781…

blog.csdn.net/pathfinder1…

清除APP缓存

www.jianshu.com/p/1859b3548…