文件的复制案例
public class Demo2 {
public static void main(String[] args) {
doCopyDir(new File("F:\\IdeaProjects"),new File("d:"));
}
public static void doCopyDir(File drc,File dis){
if(drc==null||dis==null){
System.out.println("文件不能为空");
}
if(dis.isFile()){
System.out.println("目标不能是文件");
}
if (drc.isFile()){
String name = drc.getName();
File newFile=new File(dis,name);
doCopy(drc,newFile);
}else if(drc.isDirectory()){
File newFile=new File(dis,drc.getName());
if(!newFile.exists()){
newFile.mkdirs();
}
File[] files = drc.listFiles();
if(files!=null){
for (File file : files) {
doCopyDir(file,newFile);
}
}
}
}
public static void doCopy(File drc,File dis){
BufferedWriter bufferedWriter=null;
BufferedReader bufferedReader=null;
try {
bufferedReader=new BufferedReader(new FileReader(drc));
bufferedWriter=new BufferedWriter(new FileWriter(dis));
String string=null;
while ((string=bufferedReader.readLine())!=null){
bufferedWriter.write(string);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}