现在的位置: 首页 > 综合 > 正文

复制文件或文件夹下的文件到目标文件夹

2012年12月06日 ⁄ 综合 ⁄ 共 843字 ⁄ 字号 评论关闭
  /**
* 复制文件或文件夹下的文件到目标文件夹
*
*/
private void copy(File src, File destDir) throws IOException {
if (!destDir.exists()) {
destDir.mkdirs();
} else if (!destDir.isDirectory()) {
throw new IOException("目标非文件夹");
}

if (src.isFile()) {
File destFile = new File(destDir, src.getName());
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src));
out = new BufferedOutputStream(new FileOutputStream(destFile));
byte[] buf = new byte[1024];
int len = -1;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.flush();
} catch (IOException e) {
throw e;
} finally {
if (in != null) try { in.close(); } catch (IOException e) {}
if (out != null) try { out.close(); } catch (IOException e) {}
}

} else {
File[] srcFiles = src.listFiles();
for (int i = 0, len = srcFiles.length; i < len; i++) {
if (srcFiles[i].isFile()) copy(srcFiles[i], destDir);
else copy(srcFiles[i], new File(destDir, srcFiles[i].getName()));
}
}
}

抱歉!评论已关闭.