The Android program function Copies files in the assets folder to the SD card (including subfolders) of the mobile phone and androidassets.
Recently, the function is to copy all files (including sub-files) in the asset folder to the specified directory. The method used is nothing more than AssetManager. However, the problem here is that both subfolders and subfolders must be copied. I went to Google on the Internet and searched for baidu, and found many similar problems. But it seems that there are problems. Obviously, only files in the direct asset directory can be copied, but subfolders cannot be copied. In addition, an exception is thrown when a folder is encountered. But I had to write it myself. As follows:
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 ins '.' 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 [1, 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 ();
}
}
Recursion is mainly used here, but nothing else. There is another problem here: how to determine whether the path is a folder or a file? My current method is to determine whether there is a suffix. This may be a problem.
(To: http://www.cnblogs.com/ctou45/archive/2011/06/01/2065460.html)