Android Studio中复制assets到sdcard
2017-10-11 本文已影响328人
汶水一方
- 把需要复制的文件放在src/main/assets文件夹下。
- 把需要复制的文件的文件名,存在一个字符串数组中。
private static final String FILE_NAME[] = {
"a.bin",
"b.bin",
"Readme.md"
};
- 代码
/** 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();
}