public class CopyDemo1 {
/*
* 从键盘输入源和目标路径
* 调用复制文件夹及其内容的方法,将文件夹整个复制过去
*/
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
System.out.println("请输入复制源的路径: ");
String src = sc.next();
System.out.println("请输入复制目标路径: ");
String dest = sc.next();
copyDir(new File(src), new File(dest));
}
/*
* 定义方法复制文件夹
* 参数分别传入源和目标的目录的路径
*/
public static void copyDir(File src,File dest) {
FileInputStream fis = null;
FileOutputStream fos =null;
try {
File subDest = new File(dest.getAbsolutePath() + "\\" + src.getName());
subDest.mkdirs();
File[] fileArr = src.listFiles();
for(File f : fileArr) {
if(f.isDirectory()) {
copyDir(f,subDest);
}else {
fis = new FileInputStream(f.getAbsolutePath());
fos = new FileOutputStream(subDest.getAbsolutePath() + "\\" + f.getName());
int len = 0;
byte[] bytes = new byte[1024];
while((len = fis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
fos.close();
fis.close();
}
}
}catch(IOException ex) {
System.out.println(ex);
throw new RuntimeException("读写文件失败");
}finally {
try {
if(fos != null)
fos.close();
}catch(IOException ex) {
throw new RuntimeException("释放资源失败");
}finally {
try {
if(fis != null)
fis.close();
}catch(IOException ex) {
throw new RuntimeException("释放资源失败");
}
}
}
}
}