1. 程式人生 > >Android中儲存檔案到指定路徑下

Android中儲存檔案到指定路徑下

在開發中經常會使用到儲存檔案到SD裡面。

//引數一、檔案的byte流
//引數二、檔案要儲存的路徑
//引數三、檔案儲存的名字
public static void saveFile(byte[] bfile, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;

        File file = null;
        try {
            //通過建立對應路徑的下是否有相應的資料夾。
            File dir = new
File(filePath); if (!dir.exists()) {// 判斷檔案目錄是否存在 //如果檔案存在則刪除已存在的資料夾。 dir.mkdirs(); } //如果檔案存在則刪除檔案 file = new File(filePath, fileName); if(file.exists()){ file.delete(); } fos = new
FileOutputStream(file); bos = new BufferedOutputStream(fos); //把需要儲存的檔案儲存到SD卡中 bos.write(bfile); } catch (Exception e) { e.printStackTrace(); } finally { if (bos != null) { try { bos.close(); } catch
(IOException e1) { e1.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e1) { e1.printStackTrace(); } } } }

這是在專案開發中經常會用到的方法之一,再次記錄。