java文件夹复制
用到java知识 : I/O流,递归
代码如下:
// An highlighted block
public void superCopyFile(File file,String newPath){
String oldFilePath = file.getAbsolutePath();
// 新路径 = 旧的路径以 : 截取后半部 + 需要复制的路径
String newFilePath = newPath+oldFilePath.split(":")[1];
File[] files = file.listFiles();
if(files != null ){//files不为空,证明是文件夹,但里面不一定有东西
File newFile = new File(newFilePath);
newFile.mkdirs();
System.out.println(newFile+"文件夹复制完毕");
if(files.length != 0 ){//判断是文件夹的前提,长度不为0,证明不是空文件夹
for(File f : files){
this.superCopyFile(f,newPath);
}
}
}else {//判断是文件,通过file和newFilePath建立读写文件流
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(file);
fos = new FileOutputStream(newFilePath);
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(file.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();
}
}
}
}
如果只是文件的复制就是else里面的内容