Android FileUtils 文件操作類


系統路徑

Context.getPackageName();           // 用於獲取APP的所在包目錄
Context.getPackageCodePath();       //來獲得當前應用程序對應的apk文件的路徑
Context.getPackageResourcePath();   // 獲取該程序的安裝包路徑
Context.getDatabasePath();          //返回通過Context.openOrCreateDatabase創建的數據庫文件

Environment.getDataDirectory().getPath();          // 獲得根目錄/data
Environment.getDownloadCacheDirectory().getPath();     //獲得緩存目錄/cache
Environment.getExternalStorageDirectory().getPath();   //獲得SD卡目錄/mnt/sdcard
Environment.getRootDirectory().getPath();           // 獲得系統目錄/system
//File.separator 代表 "/"

 文件操作

String path = File.getPath();//獲得文件或文件夾的絕對路徑
String path = File.getAbsoultePath();//獲得文件或文件夾的相對路徑

String parentPath = File.getParent();//獲得文件或文件夾的父目錄

String Name = File.getName();//獲得文件或文件夾的名稱

File.mkDir(); //建立文件夾
File.createNewFile();//建立文件

File[] files = File.listFiles();//列出文件夾下的所有文件和文件夾名

File.isDirectory();//true是文件夾,false是文件

File.renameTo(dest);//修改文件夾和文件名

File.delete();//刪除文件夾或文件

 資源文件assets和RW

res/raw:文件會被映射到R.java文件中,訪問的時候直接通過資源ID訪問,沒有有目錄結構

assets:不會映射到R.java文件中,通過AssetManager來訪問,能有目錄結構

//raw: 
InputStream is =getResources().openRawResource(R.raw.filename);  

//assets: 
AssetManager am =  getAssets();   
InputStream is = am.open("filename");

 從資源文件中獲取Bitmap

Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.ico);

FileUtils文件操作類

public class FileUtils {

    //檢查SDCard存在並且可以讀寫
    public static boolean isSDCardState(){
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 判斷文件是否已經存在
     *@param fileName 要檢查的文件名
     * @return boolean, true表示存在,false表示不存在
     */
    public static boolean isFileExist(String fileName) {
        File file = new File("絕對路徑" + fileName);
        return file.exists();
    }

     /**
     * 新建目錄
     * @param path 目錄的絕對路徑
     * @return 創建成功則返回true
     */
    public static boolean createFolder(String path){
        File file = new File(path);
        return file.mkdir();
    }

    /**
     * 創建文件
     *@param path 文件所在目錄的目錄名
     * @param fileName 文件名
     * @return 文件新建成功則返回true
     */
    public static boolean createFile(String path, String fileName) {
        File file = new File(path + File.separator + fileName);
        if (file.exists()) {
            return false;
        } else {
            try {
                return file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 刪除單個文件
     * @param path 文件所在的絕對路徑
     * @param fileName 文件名
     * @return 刪除成功則返回true
     */
    public static boolean deleteFile(String path, String fileName) {
        File file = new File(path + File.separator + fileName);
        return file.exists() && file.delete();
    }

    /**
     * 刪除一個目錄(可以是非空目錄)
     * @param dir 目錄絕對路徑
     */
    public static boolean deleteDirection(File dir) {
        if (dir == null || !dir.exists() || dir.isFile()) {
            return false;
        }
        for (File file : dir.listFiles()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                deleteDirection(file);//遞歸
            }
        }
        dir.delete();
        return true;
    }

    /**
     * 將字符串寫入文件
     *@param text  寫入的字符串
     * @param fileStr 文件的絕對路徑
     * @param isAppend true從尾部寫入,false從頭覆蓋寫入
     */
    public static void writeFile(String text, String fileStr, boolean isAppend) {
        try {
            File file = new File(fileStr);
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream f = new FileOutputStream(fileStr, isAppend);
            f.write(text.getBytes());
            f.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     }

    /**
     * 拷貝文件
     *@param srcPath 絕對路徑
     * @param destDir 目標文件所在目錄
     * @return boolean true拷貝成功
     */
    public static boolean copyFile(String srcPath, String destDir){
        boolean flag = false;
        File srcFile = new File(srcPath); // 源文件
        if (!srcFile.exists()){
            Log.i("FileUtils is copyFile:","源文件不存在");
            return false;
        }
        // 獲取待復制文件的文件名
        String fileName = srcPath.substring(srcPath.lastIndexOf(File.separator));
        String destPath = destDir + fileName;
        if (destPath.equals(srcPath)){
            Log.i("FileUtils is copyFile:","源文件路徑和目標文件路徑重復");
            return false;
        }
        File destFile = new File(destPath); // 目標文件
        if (destFile.exists() && destFile.isFile()){
            Log.i("FileUtils is copyFile:","該路徑下已經有一個同名文件");
            return false;
        }
        File destFileDir = new File(destDir);
        destFileDir.mkdirs();
        try{
            FileInputStream fis = new FileInputStream(srcPath);
            FileOutputStream fos = new FileOutputStream(destFile);
            byte[] buf = new byte[1024];
            int c;
            while ((c = fis.read(buf)) != -1) {
                fos.write(buf, 0, c);
            }
            fis.close();
            fos.close();
            flag = true;
        }catch (IOException e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 重命名文件
     *@param oldPath 舊文件的絕對路徑
     * @param newPath 新文件的絕對路徑
     * @return 文件重命名成功則返回true
     */
    public static boolean renameTo(String oldPath, String newPath){
        if (oldPath.equals(newPath)){
            Log.i("FileUtils is renameTo:","文件重命名失敗:新舊文件名絕對路徑相同");
            return false;
        }
        File oldFile = new File(oldPath);
        File newFile = new File(newPath);

        return oldFile.renameTo(newFile);
    }

    /**
     * 計算某個文件的大小
     *@param path 文件的絕對路徑
     *@return 文件大小
     */
    public static long getFileSize(String path){
        File file = new File(path);
        return file.length();
    }

    /**
     *計算某個文件夾的大小
     *@param  file 目錄所在絕對路徑
     * @return 文件夾的大小
     */
    public static double getDirSize(File file) {
        if (file.exists()) {
            //如果是目錄則遞歸計算其內容的總大小
            if (file.isDirectory()) {
                File[] children = file.listFiles();
                double size = 0;
                for (File f : children)
                    size += getDirSize(f);
                return size;
            } else {//如果是文件則直接返回其大小,以“兆”為單位
                return (double) file.length() / 1024 / 1024;
            }
        } else {
            return 0.0;
        }
    }

    /**
     * 獲取某個路徑下的文件列表
     * @param path 文件路徑
     * @return 文件列表File[] files
     */
    public static File[] getFileList(String path) {
        File file = new File(path);
        if (file.isDirectory()){
            File[] files = file.listFiles();
            if (files != null){
                return files;
            }else{
                return null;
            }
        }else{
            return null;
        }
    }

    /**
     * 計算某個目錄包含的文件數量
     *@param path 目錄的絕對路徑
     * @return  文件數量
     */
    public static int getFileCount(String path){
        File directory = new File(path);
        File[] files = directory.listFiles();
        return files.length;
    }

    /**
     * 獲取SDCard 總容量大小(MB)
     *@param path 目錄的絕對路徑
     * @return 總容量大小
     * */
    public long getSDCardTotal(String path){

        if(null != path&&path.equals("")){

            StatFs statfs = new StatFs(path);
            //獲取SDCard的Block總數
            long totalBlocks = statfs.getBlockCount();
            //獲取每個block的大小
            long blockSize = statfs.getBlockSize();
            //計算SDCard 總容量大小MB
            return totalBlocks*blockSize/1024/1024;

        }else{
            return 0;
        }
    }

    /**
     * 獲取SDCard 可用容量大小(MB)
     *@param path 目錄的絕對路徑
     * @return 可用容量大小
     * */
    public long getSDCardFree(String path){

        if(null != path&&path.equals("")){

            StatFs statfs = new StatFs(path);
            //獲取SDCard的Block可用數
            long availaBlocks = statfs.getAvailableBlocks();
            //獲取每個block的大小
            long blockSize = statfs.getBlockSize();
            //計算SDCard 可用容量大小MB
            return availaBlocks*blockSize/1024/1024;

        }else{
            return 0;
        }
    }
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM