檔案處理工具類,通用包檔案處理工具

來源:互聯網
上載者:User

檔案處理工具類,通用包檔案處理工具

檔案處理:

常用操作:

    獲得檔案或檔案夾的絕對路徑和相對路徑。    String path = File.getPath();//相對路徑      String path = File.getAbsoultePath();//絕對路徑          獲得檔案或檔案夾的父目錄    String parentPath = File.getParent();          獲得檔案或檔案夾的名稱    String Name = File.getName();         建立檔案或檔案夾    File.mkDir(); //建立檔案夾      File.createNewFile();//建立檔案          判斷是檔案或檔案夾    File.isDirectory()          列出檔案夾下的所有檔案和檔案夾名    File[] files = File.listFiles();          修改檔案夾和檔案名稱    File.renameTo(dest);          刪除檔案夾或檔案    File.delete(); 

 增加:

//增加    //............................................分界線...............................................    /**     * 判斷指定檔案是否存在     * @param filePath     * @return     */    public static boolean isFileExist(String filePath) {        File file = new File(filePath);        return file.exists();    }        /**     * 建立一個檔案,建立成功返回true     * @param filePath      * @return     */    public static boolean createFile(String filePath) {        try {            File file = new File(filePath);            if (!file.exists()) {                if (!file.getParentFile().exists()) {                    //建立檔案夾                      file.getParentFile().mkdirs();                }                //建立一個空的檔案                return file.createNewFile();            }        } catch (IOException e) {            e.printStackTrace();        }        return true;    }        /**     * 從一個輸入資料流裡寫到一個指定的檔案     * @param FilePath 要建立的檔案的路徑     * @param in     * @return     */    public static boolean writeFile(String FilePath, InputStream in) {        try {            //建立檔案成功則繼續,否則返回false            if (!createFile(FilePath)) {                return false;            }            FileOutputStream fos = new FileOutputStream(FilePath);            int readCount = 0;            int len = 1024;            byte[] buffer = new byte[len];            while ((readCount = in.read(buffer)) != -1) {                fos.write(buffer, 0, readCount);            }            fos.flush();            if (null != fos) {                fos.close();                fos = null;            }            if (null != in) {                in.close();                in = null;            }            return true;        } catch (IOException e) {            e.printStackTrace();        }        return false;    }        /**     * 將bitmap寫入到指定路徑的檔案裡     * @param bitmap    Bitmap對象     * @param destPath    指定的路徑     * @param quality    壓縮率,例如quality=30時,表示壓縮70%; quality=100表示不壓縮     */    public static void writeImage(Bitmap bitmap, String destPath, int quality) {        try {            FileAECS.deleteFile(destPath);            if (FileAECS.createFile(destPath)) {                FileOutputStream out = new FileOutputStream(destPath);                if (bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)) {                    out.flush();                    out.close();                    out = null;                }            }        } catch (IOException e) {            e.printStackTrace();        }    }        /**     * 將資料寫入一個檔案     *     * @param destFilePath 要建立的檔案的路徑     * @param data         待寫入的檔案資料     * @param startPos     起始位移量     * @param length       要寫入的資料長度     * @return 成功寫入檔案返回true, 失敗返回false     */    public static boolean writeFile(String destFilePath, byte[] data, int startPos, int length) {        try {            if (!createFile(destFilePath)) {                return false;            }            FileOutputStream fos = new FileOutputStream(destFilePath);            fos.write(data, startPos, length);            fos.flush();            if (null != fos) {                fos.close();                fos = null;            }            return true;        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return false;    }

刪除:

//刪除    //............................................分界線...............................................        /**     * 刪除指定檔案夾路徑下所有檔案,包括檔案夾本身     * @param filePath 檔案夾路徑     */    public static void deleteAll(String filePath){        File file = new File(filePath);        deleteFiles(file);    }        /**     * 刪除指定檔案夾下所有檔案,包括檔案夾本身     * @param file File執行個體     */    public static void deleteFiles(File file) {        if (file.isDirectory()) {            File[] listFiles = file.listFiles();            for (int i = 0; i < listFiles.length; i++) {                deleteFiles(listFiles[i]);            }        }        file.delete();    }        /**     * 刪除一個指定檔案或檔案夾     * @param filePath 需要被刪除的檔案或檔案夾的路徑     * @return     */    public static boolean deleteFile(String filePath) {        try {            File file = new File(filePath);            if (file.exists()) {                return file.delete();            }        } catch (Exception e) {            e.printStackTrace();        }        return false;    }

修改:

//修改    //............................................分界線..............................................    /**     * 批量更改指定檔案夾下所有檔案尾碼     * @param file     * @param oldSuffix     * @param newSuffix     */    public static void ReFileNameSuffix(File file, String oldSuffix, String newSuffix) {        if (file.isDirectory()) {            File[] listFiles = file.listFiles();            for (int i = 0; i < listFiles.length; i++) {                ReFileNameSuffix(listFiles[i], oldSuffix, newSuffix);            }        } else {            file.renameTo(new File(file.getPath().replace(oldSuffix, newSuffix)));        }    }        /**     * 將一個檔案拷貝到另外一個地方     * @param sourceFile    源檔案地址     * @param destFile      目的地址     * @param shouldOverlay 是否覆蓋     * @return     */    public static boolean copyFiles(String sourceFile, String destFile, boolean shouldOverlay) {        try {            if (shouldOverlay) {                deleteFile(destFile);            }            FileInputStream fi = new FileInputStream(sourceFile);            writeFile(destFile, fi);            return true;        } catch (FileNotFoundException e) {            e.printStackTrace();        }        return false;    }

讀取:

//讀取    //............................................分界線...............................................    /**     * 讀取指定檔案,返回以byte數組形式的資料     *     * @param filePath 要讀取的檔案路徑名     * @return byte數組形式的資料     */    public static byte[] readFile(String filePath) {        try {            if (isFileExist(filePath)) {                FileInputStream fi = new FileInputStream(filePath);                return readInputStream(fi);            }        } catch (FileNotFoundException e) {            e.printStackTrace();        }        return null;    }        /**     * 從一個數量流裡讀取資料,返回以byte數組形式的資料。     * 需要注意的是,如果這個方法用在從本地檔案讀取資料時,一般不會遇到問題,但如果是用於網路操作,就經常會遇到一些麻煩(網路的不穩定性,available()方法的問題)。所以如果是網路流不應該使用這個方法。     *     * @param in 要讀取的輸入資料流     * @return     * @throws java.io.IOException     */    public static byte[] readInputStream(InputStream in) {        try {            ByteArrayOutputStream os = new ByteArrayOutputStream();            byte[] b = new byte[in.available()];            int length = 0;                        while ((length = in.read(b)) != -1) {                os.write(b, 0, length);            }            b = os.toByteArray();            in.close();            in = null;            os.close();            os = null;            return b;        } catch (IOException e) {            e.printStackTrace();        }        return null;    }        /**     * 讀取網路流     *     * @param in     * @return     */    public static byte[] readNetWorkInputStream(InputStream in) {        ByteArrayOutputStream os = null;        try {            os = new ByteArrayOutputStream();            int readCount = 0;            int len = 1024;            byte[] buffer = new byte[len];            while ((readCount = in.read(buffer)) != -1) {                os.write(buffer, 0, readCount);            }            in.close();            in = null;            return os.toByteArray();        } catch (IOException e) {            e.printStackTrace();        } finally {            if (null != os) {                try {                    os.close();                } catch (IOException e) {                    e.printStackTrace();                }                os = null;            }        }        return null;    }        /**     * 從resource的raw中讀取檔案資料,只能讀取,不能寫入     * @param Context     * @param test        例如R.raw.test     * @param Charset    編碼格式 ,例如GBK、UTF-8、Unicode     * @return            String     */    public static String getRawTest(Context Context,int test,String Charset){        String String = null;        try{            //得到資源中的Raw資料流            InputStream in = Context.getResources().openRawResource(test);            //得到資料的大小            int length = in.available();                  //緩衝大小            byte [] buffer = new byte[length];            //讀取資料            in.read(buffer);            //依test.txt的編碼類別型選擇合適的編碼,如果不調整會亂碼            String = EncodingUtils.getString(buffer, Charset);            //關閉               in.close();           }catch(Exception e){              e.printStackTrace();                   }        return String;    }        /**     * 從resource的asset中讀取檔案資料,只能讀取,不能寫入     * @param Context     * @param fileName        檔案名稱     * @param Charset        編碼格式,例如GBK、UTF-8、Unicode     * @return                String     */    public static String getAssetTest(Context Context,String fileName,String Charset){        String String = null;        try{           //得到資源中的asset資料流           InputStream in = Context.getResources().getAssets().open(fileName);           //得到資料的大小           int length = in.available();            //緩衝大小           byte [] buffer = new byte[length];                  //讀取資料           in.read(buffer);                      //依test.txt的編碼類別型選擇合適的編碼,如果不調整會亂碼           String = EncodingUtils.getString(buffer, Charset);          }catch(Exception e){            e.printStackTrace();        }        return String;    }

sd卡處理相關:

//sd卡相關    //............................................分界線.........................................    /**     * 判斷SD卡是否正常掛載     * @return true正常掛載     */    public static boolean hasSDCard() {        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {            return true;        } else {            return false;        }    }        /**     * 獲得sd卡根目錄即 /sdcard     * @return    File     */    public static File getSDCardRoot(){        if(hasSDCard()){            return Environment.getExternalStorageDirectory();        }        return null;    }

擷取:

//擷取    //............................................分界線.........................................    /**     * 擷取檔案夾大小     * @param file File執行個體     * @return long 單位為M     * @throws Exception     */    public static long getFolderSize(File file) throws Exception {        long size = 0;        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();            }        }        return size / (1024*1023);    }    /**     * 獲得檔案或檔案夾的相對路徑     * @param    file     * @return    String     */    public static String getFilePath(File file){        String str = file.getPath();        return str;            }        /**     * 獲得檔案或檔案夾的絕對路徑     * @param    file     * @return    String     */    public static String getFileAbsoultePath(File file){        String str = file.getAbsolutePath();        return str;    }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.