实现目录拷贝,包括普通文件或文件夹拷贝,文件夹的拷贝会递归拷贝文件夹里面的所有子文件。需要两个参数:源文件路径,拷贝后的目标路径。例如源文件路径为A目录下的"testSrcDir"这个文件夹,想要拷贝到跟A目录同级的B目录下,则目标路径参数为"B/testSrcDir"。以下为源码:
public class PathCopyUtil {
public static void main(String[] args) throws IOException {
File srcPath = new File("src");
File destPath = new File("src_backup");
if (COPY_OK == copyDirOrFile(srcPath, destPath)) {
System.out.println("copy ok");
} else {
System.out.println("copy fail");
}
}
public static final int COPY_OK = 0;
public static final int ERROR_PATH_PARAM_NULL = 1;
public static final int ERROR_SRC_PATH_NOT_EXIST = 2;
public static final int ERROR_DEST_PATH_EXIST = 3;
public static final int ERROR_IO = 4;
public static int copyDirOrFile(File srcPath, File destPath) {
if (srcPath == null || destPath == null) {
return ERROR_PATH_PARAM_NULL;
}
if (!srcPath.exists()) {
return ERROR_SRC_PATH_NOT_EXIST;
}
if (destPath.exists()) {
return ERROR_DEST_PATH_EXIST;
}
if (srcPath.isFile()) {
return copyFile(srcPath, destPath);
} else {
return copyDir(srcPath, destPath);
}
}
private static int copyFile(File srcFile, File destFile) {
FileInputStream is = null;
FileOutputStream os = null;
try {
is = new FileInputStream(srcFile);
byte buf[] = new byte[8 * 1024];
int count = 0;
os = new FileOutputStream(destFile);
while ((count = is.read(buf)) != -1) {
os.write(buf, 0, count);
}
return COPY_OK;
} catch (IOException e) {
e.printStackTrace();
return ERROR_IO;
} finally {
closeIO(is);
closeIO(os);
}
}
private static void closeIO(Closeable io) {
if (io != null) {
try {
io.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static int copyDir(File srcDir, File destDir) {
if (!destDir.exists()) {
destDir.mkdirs();
}
for (File sub : srcDir.listFiles()) {
File dest = new File(destDir, sub.getName());
if (sub.isFile()) {
int res = copyFile(sub, dest);
if (res != COPY_OK) {
return ERROR_IO;
}
} else {
int res = copyDir(sub, dest);
if (res != COPY_OK) {
return ERROR_IO;
}
}
}
return COPY_OK;
}
}