Folder copy is wrong by recursive function under DEBUG mode on Android!!!
public class FileBox {
public static boolean copySrc2Tar(File sourceLocation, File targetLocation) {
// File sourceLocation = new File(src.getPath()); //ShallowCopy?
// File targetLocation = new File(tar.getPath()); //DeepCopy?
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
String[] children = sourceLocation.list();
for (int i = 0; i < sourceLocation.listFiles().length; i++) {
copySrc2Tar(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(sourceLocation);
out = new FileOutputStream(targetLocation);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
}
return true;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acty_mnhnflfldr);
InputStream in = null;
OutputStream out = null;
File curPath;
if(getExternalStorageState().equals(MEDIA_MOUNTED) || getExternalStorageState().equals(MEDIA_MOUNTED_READ_ONLY))
curPath = Environment.getExternalStorageDirectory();
else
curPath = Environment.getRootDirectory();
File ff = new File(curPath +File.separator +"AFolder");
File tt = new File(curPath +File.separator +"ZFolder");
FileBox.copySrc2Tar(ff, tt, true);
}
My folder hierarchy like below:
AFolder ={FolderB, textB0.txt, textB1.txt}
FolderB ={FolderC, textC0.txt}
Then run the above code, Working well under normal mode on Android Studio. 'AFolder' and its all the elements copied into 'ZFolder'. Its result is...
ZFolder ={FolderB, textB0.txt, textB1.txt}
FolderB ={FolderC, textC0.txt}
But
Under "DEBUG" mode, 'ZFolder' is not copied perfectly. Always some elements are missing.
I can NOT find out. What is problem on the above code?