java 实现文件夹整体复制(可复制单独文件)
注:使用带缓冲区的字符流实现复制
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Copy {
public static void main(String[] args) throws IOException {
String oldFileName="file01";
String newFileName="D:\\ss\\copy";
File file1 = new File(oldFileName);
File file2 = new File(newFileName,oldFileName);
System.out.println("复制开始~~~~");
copy(file1,file2);
System.out.println("复制结束~~~~");
}
public static void copy(File file1,File file2) throws IOException{
File[] files = file1.listFiles();
for (File f : files) {
if(f.isDirectory()){
File file3=new File(file2,f.getName());
if(!file3.exists()){
file3.mkdirs();
}
copy(f,file3);
}
else{
String name=f.getName();
File newFile = new File(file2,name);
if(!newFile.exists()){
newFile.createNewFile();
}
copyFile(f,newFile);
}
}
}
public static void copyFile(File oldFile ,File newFile) throws IOException{
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(oldFile));
bos = new BufferedOutputStream(new FileOutputStream(newFile));
byte[] bs = new byte[1024];
int len;
while ((len = bis.read(bs)) != -1) {
bos.write(bs, 0, len);
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
finally{
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
|