Android 拷贝Asset目录下文件或者文件夹

时间:2022-04-10 12:27:24

项目中需要拷贝Asset目录下的所有文件,因为Asset目录是只读的,操作起来不是很方便,上网搜了一些方法并不是很有效,记录一下最后的解决方案:

//path - asset下文件(夹)名称  destinationPath - 目的路径

`private void copyAssetFile(String path,String destinationPath) {
AssetManager assetManager = mContext.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() "+path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path,destinationPath);
} else {
String fullPath = destinationPath + path;
Log.i("tag", "path="+fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
if (!dir.mkdirs())
Log.i("tag", "could not create dir "+fullPath);
for (int i = 0; i < assets.length; ++i) {
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
copyAssetFileOrDir( p + assets[i],destinationPath);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}`

`private void copyFile(String filename,String destinationPath) {
AssetManager assetManager = mContext.getAssets();
InputStream in = null;
OutputStream out = null;
String newFileName = null;
try {
Log.i("tag", "copyFile() "+filename);
in = assetManager.open(filename);
newFileName = destinationPath + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", "Exception in copyFile() of "+newFileName);
Log.e("tag", "Exception in copyFile() "+e.toString());
}
}`