最近在做個功能是將asset文件夾下的所有文件(包括子文件)全部拷貝出來到指定目錄下。所用的方法無非是用AssetManager。但是這里有個問題是也要講子文件夾和子文件都要拷貝出來。到網上Google了下,也到baidu搜索了下,發現了很多類似問題。但好像都有問題。顯然只能做到將asset直接目錄下的文件拷貝出來,但子文件夾拷貝不出來,而且,碰到文件夾,會拋異常。無奈自己只好動手寫了個。如下:
private void CopyAssets(String assetDir,String dir) {
String[] files;
try
{
files = this.getResources().getAssets().list(assetDir);
}
catch (IOException e1)
{
return;
}
File mWorkingPath = new File(dir);
//if this directory does not exists, make one.
if(!mWorkingPath.exists())
{
if(!mWorkingPath.mkdirs())
{
}
}
for(int i = 0; i < files.length; i++)
{
try
{
String fileName = files[i];
//we make sure file name not contains '.' to be a folder.
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();
} iphone拍照小技巧
catch (IOException e)
{
e.printStackTrace();
}
}
這里主要用到了遞歸,其他倒是沒有什么。倒是這里還有個存在的問題:如何判斷路徑的是個文件夾還是文件,我目前使用的方法就是判斷有沒有后綴,這個可能存在問題。