您的位置:首页 > 其它

把assets下的指定文件拷贝到sdcard上

2013-08-06 14:18 302 查看
由于res下的values、xml等资源文件是不可更改的所以可以把文件放到assets下,放到sdcard上,然后在进行修改。

方法如下:

AssetManager assets = getResources().getAssets();


try {
//判断sdcard是否存在
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED)) {

String xmlPath = File.separator + "sdcard" + File.separator+"appserver.xml";
File outFile = new File(xmlPath);
if(!outFile.exists()){
System.out.println("--建立文件---");
//outFile.mkdirs();
//创建不存在的文件,如果没有这句会出现找不到文件的异常
outFile.createNewFile();
//取到assets下的指定文件,变成流
InputStream in = assets.open("appserver.xml");
//向指定新文件里写入
FileOutputStream out = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) >=0)
{
out.write(buf, 0, len);
}
//关闭流
in.close();
out.close();
}

} else {
System.out.println("sdcard不存在");
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


也可以把assets下的文件进行遍历
private void CopyAssets(String assetDir, String dir) {
String[] files;
try {
// 获得Assets一共有几多文件
files = this.getResources().getAssets().list(assetDir);
} catch (IOException e1) {
return;
}
File mWorkingPath = new File(dir);
// 如果文件路径不存在
if (!mWorkingPath.exists()) {
// 创建文件夹
if (!mWorkingPath.mkdirs()) {
// 文件夹创建不成功时调用
}
}

for (int i = 0; i < files.length; i++) {
try {
// 获得每个文件的名字
String fileName = files[i];
// 根据路径判断是文件夹还是文件
if (!fileName.contains(".")) {
if (0 == assetDir.length()) {
CopyAssets(fileName, dir + fileName + "/");
} else {
CopyAssets(assetDir + "/" + fileName, dir + "/"
+ fileName + "/");
}
continue;
}
File outFile = new File(mWorkingPath, fileName);
if (outFile.exists())
outFile.delete();
InputStream in = null;
if (0 != assetDir.length())
in = getAssets().open(assetDir + "/" + fileName);
else
in = getAssets().open(fileName);
OutputStream out = new FileOutputStream(outFile);

// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}

in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}

catch (IOException e) {
e.printStackTrace();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: