1. 程式人生 > >android:將assets目錄下的檔案(資料夾)放置到記憶體卡指定目錄下

android:將assets目錄下的檔案(資料夾)放置到記憶體卡指定目錄下

最近做一個OCR識別圖片文字的功能,閒暇之餘,提取專案中涉及的方法供大家參考.
這個方法是將assets下的指定檔案或資料夾,放置到sd的指定目錄下,程式碼中都有註釋.
當然我們也可以探討探討OCR.
	/**
	 * 將assets下的檔案放到sd指定目錄下
	 * 
	 * @param context
	 *            上下文
	 * @param assetsPath
	 *            assets下的路徑
	 * @param sdCardPath
	 *            sd卡的路徑
	 */
	public static void putAssetsToSDCard(Context context, String assetsPath,
            String sdCardPath) {
        try {
            String mString[] = context.getAssets().list(assetsPath);
            if (mString.length == 0) { // 說明assetsPath為空,或者assetsPath是一個檔案
                InputStream mIs = context.getAssets().open(assetsPath); // 讀取流
                byte[] mByte = new byte[1024];
                int bt = 0;
                File file = new File(sdCardPath + File.separator
                        + assetsPath.substring(assetsPath.lastIndexOf('/')));
                if (!file.exists()){
                    file.createNewFile(); // 建立檔案
                }else{
                    return;//已經存在直接退出
                }
                    FileOutputStream fos = new FileOutputStream(file); // 寫入流
                    while ((bt = mIs.read(mByte)) != -1) { // assets為檔案,從檔案中讀取流
                        fos.write(mByte, 0, bt);// 寫入流到檔案中
                    }
                    fos.flush();// 重新整理緩衝區
                    mIs.close();// 關閉讀取流
                    fos.close();// 關閉寫入流
                }
            } else { // 當mString長度大於0,說明其為資料夾
                sdCardPath = sdCardPath + File.separator + assetsPath;
                File file = new File(sdCardPath);
                if (!file.exists())
                    file.mkdirs(); // 在sd下建立目錄
                for (String stringFile : mString) { // 進行遞迴
                    putAssetsToSDCard(context, assetsPath + File.separator
                            + stringFile, sdCardPath);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }