[英]Copy File Assets To SDCard Activity (Android app) need ideas
I need to copy all folders inside Assets to specific folder on SDCARD. 我需要将资产内的所有文件夹复制到SDCARD上的特定文件夹。 Lets say our target folder called "RESULT_HERE" under folder called "MAIN_FOLDER" 假设我们的目标文件夹“ RESULT_HERE”位于“ MAIN_FOLDER”文件夹下
I used this code but no result at all. 我使用了这段代码,但完全没有结果。 Can't copy files or even create the folders. 无法复制文件,甚至无法创建文件夹。 I used this code . 我用了这段代码 。
Any ideas? 有任何想法吗?
I modify a code to copy all folders and files with the same structure of Assets folder. 我修改了一个代码,以复制具有Assets文件夹相同结构的所有文件夹和文件。 Just replace the code of CopyFiles method. 只需替换CopyFiles方法的代码即可。
private void CopyFiles(String sdCardPath, String assetFilename){
AssetManager assetManager = getAssets();
try {
String[] files = assetManager.list(assetFilename);
//Try as file
if(files.length == 0){
InputStream in;
OutputStream out;
String fileName = assetFilename.substring(assetFilename.lastIndexOf(File.separator) + 1);
File file = new File(sdCardPath + File.separator + assetFilename.substring(0, assetFilename.length() - fileName.length()));
if(!file.exists())
file.mkdir();
in = assetManager.open(assetFilename);
out = new FileOutputStream(file.getAbsolutePath() + File.separator + fileName);
copyFile(in, out);
in.close();
out.flush();
out.close();
}
//Try as folder
else{
for (String assetFile : files){
String newAssetFilename = assetFilename.length() > 0
? assetFilename + File.separator +assetFile // Is on internal folder
: assetFile; // Is on root of asset folder
CopyFiles(sdCardPath, newAssetFilename);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
To call this function you must invoke : 要调用此函数,您必须调用:
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
CopyFiles(Environment.getExternalStorageDirectory() + File.separator + INTERNAL_PATH, "");
where INTERNAL_PATH is the relative path of your folder. 其中INTERNAL_PATH是文件夹的相对路径。 The function Environment.getExternalStorageState() is to ensure that SD Card is present. 函数Environment.getExternalStorageState()用于确保存在SD卡。
Also, remember then you must declare a follow permission on Manifest: 另外,请记住,那么您必须在Manifest上声明关注权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.