美文网首页
Android Studio中复制assets到sdcard

Android Studio中复制assets到sdcard

作者: 汶水一方 | 来源:发表于2017-10-11 04:27 被阅读328次
  1. 把需要复制的文件放在src/main/assets文件夹下。
  1. 把需要复制的文件的文件名,存在一个字符串数组中。
private static final String FILE_NAME[] = {
    "a.bin",
    "b.bin",
    "Readme.md"
};
  1. 代码
/** check whether there is a /sdcard/test/ folder in the phone **/
/** if not, create one                                         **/
File testFolder = new File(Environment.getExternalStorageDirectory() + "/test");
if(testFolder.exists() && testFolder.isDirectory() ) {
    Log.d("", "test folder already exists");
} else if(!testFolder.exists()) {
    testFolder.mkdir();
}

/** check whether the model files exist in the phone **/
/** if not, copy them to there                       **/
for (int n =0; n < FILE_NAME.length; n++) {
    File modelFile = new File(testFolder, FILE_NAME[n]);
    if (!modelFile.exists()) {
        copyAssetFilesToSDCard(modelFile, FILE_NAME[n]);
    }
}

函数:

private void copyAssetFilesToSDCard(final File testFileOnSdCard, final String FileToCopy) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    InputStream is = getAssets().open(FileToCopy);
                    FileOutputStream fos = new FileOutputStream(testFileOnSdCard);
                    byte[] buffer = new byte[8192];
                    int read;
                    try {
                        while ((read = is.read(buffer)) != -1) {
                            fos.write(buffer, 0, read);
                        }
                    } finally {
                        fos.flush();
                        fos.close();
                        is.close();
                    }
                } catch (IOException e) {
                    Log.d("", "Can't copy test file onto SD card");
                }
            }
        }).start();
}

相关文章

网友评论

      本文标题:Android Studio中复制assets到sdcard

      本文链接:https://www.haomeiwen.com/subject/gkjiyxtx.html