6.练习_复制目录下所有文件
学习:第7遍
1.练习:复制目录下所有文件 复制指定目录"c:/aaa/old"下所有文件复制到"c:/aaa/new"
public class Test{
public static void main(String
[] args
) {
String oldStr
="c:/aaa/old";
String newStr
="c:/aaa/new";
copyFile(oldStr
,newStr
);
}
private static void copyFile(String oldPath
, String newPath
) {
File oldFile
= new File(oldPath
);
File newFile
= new File(newPath
);
if(oldFile
.isDirectory()){
newFile
=new File(newPath
+File
.separator
+oldFile
.getName());
newFile
.mkdirs();
File
[] listFiles
= oldFile
.listFiles();
for (File file
: listFiles
) {
copyFile(file
.getAbsolutePath(), newFile
.getAbsolutePath());
}
}else if(oldFile
.isFile()){
try(
FileInputStream fis
= new FileInputStream(oldPath
);
FileOutputStream fos
= new FileOutputStream(newPath
+File
.separator
+oldFile
.getName());
){
int num
=-1;
byte[] buffer
=new byte[1024];
while((num
=fis
.read(buffer
))!=-1){
fos
.write(buffer
,0,num
);
}
System
.out
.println("复制"+oldPath
+"到"+newPath
+"成功");
} catch (FileNotFoundException e
) {
e
.printStackTrace();
} catch (IOException e
) {
e
.printStackTrace();
}
}
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-22367.html