当以下代码使用更多数量的嵌套文件夹和文件执行时,它会给出 StackOverflowException 请建议我避免它的方法。
public void copyDirectory(File sourceLocation , File targetLocation){
try {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists() && !targetLocation.mkdirs()) {
throw new IOException("Cannot create dir " + targetLocation.getAbsolutePath());
}
String[] children = sourceLocation.list();
String s;
if (children != null && children.length > 0) {
for (int i = 0; i < children.length; i++) {
s = children[i];
copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
}
}
} else {
// make sure the directory we plan to store the recording in exists
File directory = targetLocation.getParentFile();
if (directory != null && !directory.exists() && !directory.mkdirs()) {
throw new IOException("Cannot create dir " + directory.getAbsolutePath());
}
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
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) {
// TODO Auto-generated catch block
addError(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
addError(e.getMessage());
e.printStackTrace();
}
}
请建议所需的增强功能。
谢谢你