62,623
社区成员
发帖
与我相关
我的任务
分享public static void copyFolder(File source, File target) throws Exception {
System.out.println(source.getAbsolutePath());
if (source.isDirectory()) {
if (source.isFile()) {
copyFile(source, target);
System.out.println( "是文件 ");
} else {
System.out.println( "是目录 ");
/** 应该是这个语句出现的问题,应该创建目标文件夹而不是源文件夹 */
target.mkdirs();
}
File[] a = source.listFiles();
for (int i = 0; i < a.length; i++) {
copyFolder(a[i], target);
}
}
}package com.wepull.io.lesson01.homework;
import java.io.*;
public class hk4 {
public void fun(String s1,String s2){
File f1=new File(s1);//先将传进来的两个目录转换为File对象
File f2=new File(s2);
hk5 hk=new hk5();//事先做了个复制的方法,就直接拿来用了,方法在下面
File[]f=f1.listFiles();//将源目录的文件生成一个File类型的数组
if(f.length==0){//如果数组的长度为空,即目录为空,则直接创建目标目录即可{f3.mkdirs();}
File f3=new File(s2);
f3.mkdirs();
}
for (int i = 0; i < f.length; i++) {//如果数组的长度不为空,即目录不空,
if(f[i].isFile()){//如果第i个文件是文件,则调用方法复制文件
hk.copyfile(s1+"/"+f[i].getName(),s2+"/"+f[i].getName());
}else if(f[i].isDirectory()){//如果第i个文件是目录,先创建目标目录即可{f3.mkdirs();}
String s3=s2+"/"+f[i].getName();
File f3=new File(s3);
f3.mkdirs();
fun(f[i].getPath(),s2+"/"+f[i].getName());//然后将该目录和目标创建好的目录作为源目录和目标目录调用方法
}
}
}
public void fun2() {
}
public static void main(String[] args) {
hk4 hk=new hk4();
String s1="e:/io";
String s2="e:/oi";
hk.fun(s1, s2);
}
}
class hk5 {
/**
* 用BufferedReader和PrintStream来复制
*/
public void copyfile(String s1,String s2) {
try {
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(s1)));
PrintStream ps=new PrintStream(new FileOutputStream(s2));
String len;
while((len=br.readLine())!=null){
ps.println(len);
}
br.close();
ps.flush();
ps.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}