溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

android 文件管理工具類

發(fā)布時間:2020-06-29 22:13:40 來源:網(wǎng)絡 閱讀:545 作者:fstx 欄目:移動開發(fā)


import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.StatFs;

import com.badou.mworking.net.DownloadListener;

public class FileUtils {
    private static int FILESIZE = 4 * 1024;
    
    /**
     * 檢查是否存在SDCard
     *
     * @return
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
    
    public static String getSDPath(Context context){
        if(hasSdcard()){
            return Environment.getExternalStorageDirectory().getPath()+"/";
        }else{
            return context.getFilesDir()+"/";
        }
    }
    
    /**
     * 判斷SD卡上的文件夾是否存在
     *
     * @param fileName
     * @return
     */
    public static boolean isFileExist(String fileName) {
        File file = new File(fileName);
        return file.exists();
    }

    /**
     * 將一個InputStream里面的數(shù)據(jù)寫入到SD卡中
     *
     * @param path
     * @param fileName
     * @param input
     * @return
     */
    public static File write2SDFromInput(String path, InputStream input,
            DownloadListener downloadListener) {
        File file = null;
        OutputStream output = null;
        try {
            file = new File(path);
            if (file.exists())
                file.delete();
            file.createNewFile();

            output = new FileOutputStream(file);
            byte[] buffer = new byte[FILESIZE];

            int totalLength = 0;
            int length;
            while ((length = (input.read(buffer))) > 0) {
                output.write(buffer, 0, length);
                totalLength += length;
                if (downloadListener != null)
                    downloadListener.onDownloadSizeChange(totalLength);
            }

            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 復制文件
     *
     * @param srcPath
     *            源文件絕對路徑
     * @param destPath
     *            目標文件所在目錄
     * @return boolean
     */
    private static boolean copyFile(String srcPath, String destPath) {
        boolean flag = false;

        File srcFile = new File(srcPath);
        if (!srcFile.exists()) { // 源文件不存在
            System.out.println("源文件不存在");
            return false;
        }
        if (destPath.equals(srcPath)) { // 源文件路徑和目標文件路徑重復
            System.out.println("源文件路徑和目標文件路徑重復!");
            return false;
        }
        File destFile = new File(destPath);
        if (destFile.exists()) { // 該路徑下已經(jīng)有一個同名文件
            deleteGeneralFile(destPath);
        }
        try {
            FileInputStream fis = new FileInputStream(srcFile);
            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();
        }

        if (flag) {
            System.out.println("復制文件成功!");
        }

        return flag;
    }

    /**
     * 刪除文件或文件夾
     *
     * @param path
     *            待刪除的文件的絕對路徑
     * @return boolean
     */
    public static boolean deleteGeneralFile(String path) {
        boolean flag = false;

        File file = new File(path);
        if (!file.exists()) { // 文件不存在
            System.out.println("要刪除的文件不存在!");
        }

        if (file.isDirectory()) { // 如果是目錄,則單獨處理
            flag = deleteDirectory(file.getAbsolutePath());
        } else if (file.isFile()) {
            flag = deleteFile(file);
        }

        if (flag) {
            System.out.println("刪除文件或文件夾成功!");
        }

        return flag;
    }

    /**
     * 刪除文件
     *
     * @param file
     * @return boolean
     */
    private static boolean deleteFile(File file) {
        return file.delete();
    }

    /**
     * 刪除目錄及其下面的所有子文件和子文件夾,注意一個目錄下如果還有其他文件或文件夾
     * 則直接調(diào)用delete方法是不行的,必須待其子文件和子文件夾完全刪除了才能夠調(diào)用delete
     *
     * @param path
     *            path為該目錄的路徑
     */
    private static boolean deleteDirectory(String path) {
        boolean flag = true;
        File dirFile = new File(path);
        if (!dirFile.isDirectory()) {
            return flag;
        }
        File[] files = dirFile.listFiles();
        for (File file : files) { // 刪除該文件夾下的文件和文件夾
            // Delete file.
            if (file.isFile()) {
                flag = deleteFile(file);
            } else if (file.isDirectory()) {// Delete folder
                flag = deleteDirectory(file.getAbsolutePath());
            }
            if (!flag) { // 只要有一個失敗就立刻不再繼續(xù)
                break;
            }
        }
        flag = dirFile.delete(); // 刪除空目錄
        return flag;
    }

    /**
     * 由上面方法延伸出剪切方法:復制+刪除
     *
     * @param destPath
     *            同上
     */
    public static boolean cutGeneralFile(String srcPath, String destPath) {
        if (!copyFile(srcPath, destPath)) {
            System.out.println("復制失敗導致剪切失敗!");
            return false;
        }
        if (!deleteGeneralFile(srcPath)) {
            System.out.println("刪除源文件(文件夾)失敗導致剪切失敗!");
            return false;
        }

        System.out.println("剪切成功!");
        return true;
    }

    public static void writeBitmap2SDcard(Bitmap bitmap, String path) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        byte[] byteArray = baos.toByteArray();
        try {
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(byteArray);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 功能描述:獲取sd卡的剩余空間
     * @return
     */
    public static long getAvailaleSize() {
        File path = Environment.getExternalStorageDirectory();// 取得sdcard文件路徑
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
        // (availableBlocks * blockSize)/1024 KIB 單位
        // (availableBlocks * blockSize)/1024 /1024 MIB單位
    }
    
    /**
     * 功能描述: 通過遞歸的方法獲取文件夾內(nèi)文件的大小
     * @param file
     * @return
     * @throws Exception
     */
    public static long getFileSize(File file) throws Exception{  
        long size = 0;  
        File flist[] = file.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;  
    }  
    
    /**
     * 遞歸刪除目錄下的所有文件及子目錄下所有文件
     * @param dir 將要刪除的文件目錄
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //遞歸刪除目錄中的子目錄下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目錄此時為空,可以刪除
        return dir.delete();
    }
    
    /**
     * 功能描述: 微培訓文件緩存目錄
     */
    public static String getTrainCacheDir(Context context){
        String filePath = context.getExternalFilesDir(
                Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
                + File.separator + "train";
        File file = new File(filePath);
        if(!file.exists()){
            file.mkdirs();
            return filePath +  File.separator;
        }
        return filePath+File.separator;
    }
    
    public static String getTongSHQDir(Context context){
        String filePath = context.getExternalFilesDir(
                Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
                + File.separator + "tongshiquan";
        File file = new File(filePath);
        if(!file.exists()){
            file.mkdirs();
            return filePath +  File.separator;
        }
        return filePath+File.separator;
    }
    
    public static long getAvailableStorage() {
        String storageDirectory = null;  //存儲目錄
        storageDirectory = Environment.getExternalStorageDirectory().toString(); //獲取外部存儲目錄

        try {
            /**
             * StatFs Retrieve overall information about the space on a filesystem.
             * 返回關于文件系統(tǒng)空間的所有信息
             * Android.os下的StatFs類主要用來獲取文件系統(tǒng)的狀態(tài),能夠獲取sd卡的大小和剩余空間,獲取系統(tǒng)內(nèi)部空間也就是/system的大小和剩余空間等等。
             * */
            StatFs stat = new StatFs(storageDirectory);
            long avaliableSize = ((long) stat.getAvailableBlocks() * (long) stat.getBlockSize());
            return avaliableSize;
        } catch (RuntimeException ex) {
            return 0;
        }
    }
    
    /**文件重命名
     * @param path 文件目錄
     * @param oldname  原來的文件名
     * @param newname 新文件名
     */
     public static void renameFile(String path,String oldname,String newname){
         if(!oldname.equals(newname)){//新的文件名和以前文件名不同時,才有必要進行重命名
             File oldfile=new File(path+"/"+oldname);
             File newfile=new File(path+"/"+newname);
             if(!oldfile.exists()){
                 return;//重命名文件不存在
             }
             if(newfile.exists())//若在該目錄下已經(jīng)有一個文件和新文件名相同,則不允許重命名
                 System.out.println(newname+"已經(jīng)存在!");
             else{
                 oldfile.renameTo(newfile);
             }
         }else{
             System.out.println("新文件名和舊文件名相同...");
         }
     }
}

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI