复制文件:
//设计一个方法---->文件复制
public void copyFile(File file,String path){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File newFile = new File(path+"//"+file.getName());
fis = new FileInputStream(file);
fos = new FileOutputStream(newFile);
byte[] b = new byte[1000];
int count = fis.read(b);
while(count!=-1){
fos.write(b,0,count);
fos.flush();
count = fis.read(b);
}
System.out.println("复制成功!");
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fis!=null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {//为了保证程序的健壮性 各自关各自的 不会因为一个出现异常另一个关不上
if(fos!=null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
复制文件夹:
//复制文件夹
public void copyFiles(File file,String newPath){
//获取当前file对象的绝对路径
String oleFilePath = file.getAbsolutePath();//比如E://test//bbb
String newFilePath = newPath+oleFilePath.split(":")[1];////拼接path得到新路径 D://test//test//bbb
//创建一个新的file对象
File newFile = new File(newFilePath);//此时路径为 D://test//test//bbb
//获取当前传进来的file对象的所有子元素
File[] files = file.listFiles();
//判断当前传进来的file对象是文件夹还是文件
if(files!=null){//子元素不为空 就是文件夹 所以先复制文件夹
//再通过这个新的newFile对象 在硬盘上创建一个文件夹
//当前的创建路径为 D://test//test//bbb 在D盘这个路径可能不存在所以需要用mkdirs();
newFile.mkdirs();
System.out.println(newFile.getName()+"文件夹复制完毕");
//如果文件夹里面还有元素 继续复制
if(files.length!=0){//只有file对象是文件夹时才会进行递归
//所以这段代码可以放在文件夹的if分支里
//还可以把if()中重复的 files!=null 这个判断条件省略
for(File f:files) {
this.copyFiles(f,newPath);//递归 将文件夹里的元素全部复制过来
}
}
}else{//file是一个文件
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(file);
fos = new FileOutputStream(newFile);
byte[] b = new byte[1024];
int count = fis.read(b);
while(count!=-1){
fos.write(b,0,count);
fos.flush();
count = fis.read(b);
}
System.out.println(newFile.getName()+"文件复制完毕");
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fis!=null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fos!=null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}