import org.junit.Test;
import java.io.*;
public class CopyTest {
@Test
public void test1(){
dir("xxx","xxx"); //输入原文件的路径和目标路径
//copy(file);
}
private void dir(String src,String des) {
File file = new File(src); //获取源目录文件
File[] files = file.listFiles(); //展开到数组
if(files == null){
return;
}
if(!(new File(des).exists()))
new File(des).mkdirs(); //对于已经确定是目录的外部des先创建目录
for (int i = 0; i < files.length; i++) { //对des内部的文件遍历
if (files[i].isFile()) { //判断是文件还是目录
copy(files[i].getPath(),des+File.separator+files[i].getName());//文件的当前路径作为源路径,目标路径即文件名
} else if (files[i].isDirectory()){
dir(files[i].getPath(),des+File.separator+files[i].getName()); // 子目录必须也得重新统计, 递归调用,目标路径加上文件名称作为下次迭代的新路径
}
}
}
public void copy(String src,String des){
FileInputStream fio =null;
//BufferedInputStream bio = null;
FileOutputStream foo = null;
//BufferedOutputStream boo = null;
try {
fio =new FileInputStream(src);
// bio = new BufferedInputStream(fio);
foo = new FileOutputStream(des);
// boo = new BufferedOutputStream(foo);
byte[] ch = new byte[8192];
int n;
while((n=fio.read(ch))!=-1){
foo.write(ch,0,n);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fio!=null){
try {
fio.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(foo!=null){
try {
foo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
java文件的复制(含目录)
最新推荐文章于 2022-06-27 17:45:57 发布