文件處理工具類

来源:http://www.cnblogs.com/hznu-zhb/archive/2016/03/28/5329340.html
-Advertisement-
Play Games

文件處理: 常用操作: 增加: 刪除: 修改: 讀取: sd卡處理相關: 獲取: ...


文件處理:

常用操作:

    獲得文件或文件夾的絕對路徑和相對路徑。
    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;
    }

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在以前我們的博客文章中,我們討論了在web設計和開發項目中使用Twitter Bootstrap的好處。Twitter Bootstrap也有很多的缺點。讓我們看看這些主要的問題: 1,它不遵循最佳實踐 我們在使用Twitter Bootstrap時遇到的最大問題之一是你的DOM元素上將擁擠大量的類 ...
  • × 目錄 [1]white-space [2]word-wrap [3]word-break 前面的話 CSS3新增了兩個換行屬性word-wrap和word-break。把空白符和換行放在一起說,是因為實際上空白符是包括換行的,且常用的文本不換行是使用的空白符的屬性white-space: now ...
  • 這篇博文基於上一篇iOS_CNBlog項目開發 (基於博客園api開發)所寫. 過了剛好兩個星期, 這次基於上一次的1.0版本, 完善了新的功能, 也修複了之前的一些bug, 算是完成1.1版本吧, 一次進步一下點總是好的, 貼上github:)地址, 喜歡的可以玩弄玩弄 https://githu ...
  • UIAlertView 與 UIActionSheet UIAlertView 樣式 實現 註意 其“確定”按鈕的顏色與“取消”按鈕的外觀一樣(沒有顯示紅色,即 normal) UIActionSheet 樣式 實現 註意 其“確定”按鈕的顏色與“取消”按鈕的外觀不一樣(顯示紅色,即 destruc ...
  • 這一篇主要來講一下自定義控制項中的自定義viewgroup,我們以項目中最常用的下拉刷新和載入更多組件為例 簡單介紹一下自定義viewgroup時應該怎麼做。 分析:下拉刷新和載入更多的原理和步驟 自定義一個viewgroup,將headerview、contentview和footerview從上到 ...
  • J2ObjC 是一個Google開發的開源工具,用於將Java代碼轉換為Objective-C代碼。其目的是為了能在iOS平臺上重用Android平臺、web伺服器端的Java代碼。伺服器端代碼的轉換由 GWT 完成。J2ObjC並不轉換UI代碼,這部分需要針對不同平臺分別開發。 我們在2012年發 ...
  • public class NetStateUtils { /** * 對網路連接狀態進行判斷 * * @return true, 可用; false, 不可用 */ public static boolean isNetworkConnected(Context context) { if (con ...
  • 相關的第三方類庫大家可以去github上下載 1.NSJSONSerialization 具體代碼如下 : 2.JSONKit 這是需要導入第三方類庫 3.SBJson 同樣需要導入第三方類庫 4.TouchJson 第三方類庫 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...