Java File 文件操作

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

取得文件夹大小 long 单位为M

    public static long getFileSize(File f) throws Exception {  
        long size = 0;  
        File flist[] = f.listFiles();  
        for (int i = 0; i < flist.length; i++) {  
            if (flist[i].isDirectory()) {  
                size = size + getFileSize(flist[i]);  
            } else {  
                size = size + flist[i].length();  
            }  
        }  
        return size;  
    }  

转换文件大小

public static String FormetFileSize(long fileS) {  
        DecimalFormat df = new DecimalFormat("#.00");  
        String fileSizeString = "";  
        if (fileS == 0) {  
            fileSizeString = "0KB";  
        } else if (fileS < 1024) {  
            fileSizeString = df.format((double) fileS) + "B";  
        } else if (fileS < 1048576) {  
            fileSizeString = df.format((double) fileS / 1024) + "KB";  
        } else if (fileS < 1073741824) {  
            fileSizeString = df.format((double) fileS / 1048576) + "MB";  
        } else {  
            fileSizeString = df.format((double) fileS / 1073741824) + "G";  
        }  
        return fileSizeString;  
    }  

删除指定目录下文件及目录

public static void deleteFolderFile(String filePath, boolean deleteThisPath)  
            throws IOException {  
        if (!TextUtils.isEmpty(filePath)) {  
            File file = new File(filePath);  
            if (file.isDirectory()) {// 处理目录  
                File files[] = file.listFiles();  
                for (int i = 0; i < files.length; i++) {  
                    deleteFolderFile(files[i].getAbsolutePath(), true);  
                }  
            }  
            if (deleteThisPath) {  
                // 如果是文件,删除  
                if (!file.isDirectory()) {  
                    file.delete();  
                } else {  
                    // 目录下没有文件或者目录,删除  
                    if (file.listFiles().length == 0) {  
                        file.delete();  
                    }  
                }  
            }  
        }  
    }  

    /** 
     * 获取文件名 
     *  
     * @param path 
     * @return 
     */  
    public static String getFileName(String path) {  
        int start = path.lastIndexOf("/") + 1;  
        return path.substring(start);  
    }  
      
    /** 
     * 获取文件名 
     *  
     * @param file 
     * @return 
     */  
    public static String getFileName(File file) {  
        String filePath = file.getAbsolutePath();  
        return getFileName(filePath);  
    }