都是关于文件复制的,一个是字符流,一个是字节流
字符流
然后结果复制后的文件乱码
字节流的是一个实例,
public static void copyDirectory() throws IOException {
Scanner sc=new Scanner(System.in);
System.out.println("请输入源目录位置:");
String srcPath=sc.nextLine();//从控制台获取路径
File srcFile=new File(srcPath);
System.out.println("请输入目标位置:");
String destPath=sc.nextLine();//从控制台获取路径
File destFile=new File(destPath);
//将源路径中的内容复制到目标路径下
FileUtils.copySrcPathTODestPath(srcFile,destFile);
}
public static void copySrcPathTODestPath(File srcFile,File destFile) throws IOException {
//创建目的地文件夹
destFile.mkdirs();/*创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。*/
//获取源路径中的所有File对象
File[] files=srcFile.listFiles();
for (File file:files
) {
File dest=new File(destFile,file.getName());
//判断当前file对象是否为目录
if(file.isDirectory()){
//通过递归,完成复制目录
copySrcPathTODestPath(file,dest);
}else{
//复制文件
FileInputStream in=new FileInputStream(file);
FileOutputStream out=new FileOutputStream(dest);
//读
byte[] bys=new byte[1024];
int len=0;
while((len=in.read(bys))!=-1){
//写
out.write(bys,0,len);
}
//关闭流
in.close();
out.close();
}
}
}
当我设置好源目录和目标目录的执行的时候
目标目录如果是源目录的子文件夹就会无限复制,最后炸掉,我猜可能是递归的问题,但我不知道怎么解决他。
正常: 源目录 :F:\api 目标目录: D:\Program Files
无限复制:源目录:D:\Program Files\Java 目标目录:D:\Program Files\Java\123
求大神帮帮我。感激不尽