1. 程式人生 > >【Android】複製assets裡的單檔案到指定資料夾

【Android】複製assets裡的單檔案到指定資料夾

轉載請註明出處,原文連結:https://blog.csdn.net/u013642500/article/details/80069811


本方法使用前提是已擁有許可權,未對許可權不足情況進行處理,如有需要可自行新增。

關於讀寫許可權的總結請參考:https://blog.csdn.net/u010784887/article/details/53560025

    /**
     * 複製單個檔案
     *
     * @param outPath String 輸出檔案路徑 如:data/user/0/com.test/files
     * @param fileName String 要複製的檔名 如:abc.txt
     * @return <code>true</code> if and only if the file was copied; <code>false</code> otherwise
     */
    private boolean copyAssetsSingleFile(String outPath, String fileName) {
        File file = new File(outPath);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                Log.e("--Method--", "copyAssetsSingleFile: cannot create directory.");
                return false;
            }
        }
        try {
            InputStream inputStream = getAssets().open(fileName);
            File outFile = new File(file, fileName);
            FileOutputStream fileOutputStream = new FileOutputStream(outFile);
            // Transfer bytes from inputStream to fileOutputStream
            byte[] buffer = new byte[1024];
            int byteRead;
            while (-1 != (byteRead = inputStream.read(buffer))) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            inputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

/**
 * 複製單個檔案
 *
 * @param outPath String 輸出檔案路徑 如:data/user/0/com.test/files
 * @param fileName String 要複製的檔名 如:abc.txt
 * @return <code>true</code> if and only if the file was copied; <code>false</code> otherwise
 */
private boolean copyAssetsSingleFile(String outPath, String fileName) {
    File file = new 
File(outPath); if (!file.exists()) { if (!file.mkdirs()) { Log.e("--Method--", "copyAssetsSingleFile: cannot create directory."); return false; } } try { InputStream inputStream = getAssets().open(fileName); File outFile = new File(file,
fileName); FileOutputStream fileOutputStream = new FileOutputStream(outFile); // Transfer bytes from inputStream to fileOutputStream byte[] buffer = new byte[1024]; int byteRead; while (-1 != (byteRead = inputStream.read(buffer))) { fileOutputStream.write(buffer, 0, byteRead); } inputStream.close(); fileOutputStream.flush(); fileOutputStream.close(); return true; } catch (IOException e) { e.printStackTrace(); return false; } }


由於本人安卓知識及技術有限,程式碼如有錯誤或不足請評論指出,非常感謝!