思路分析
上一篇文章已经介绍了java实现文件夹的复制,这篇文章为上一篇文章的补充,补充了文件夹的剪切,大家可以点击这里来了解上一篇文章(Java实现文件夹的复制)
代码展示
package com.java.study;
import java.util.*;
import java.io.*;
public class Test implements Serializable{
private String src;
private String target;
public Test(String src, String target) {
this.src = src;
this.target = target;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
static void copyfile(String oldfile,String newfile) throws IOException {
File oldf=new File(oldfile);
FileOutputStream fop=new FileOutputStream(new File(newfile));
FileInputStream fip=new FileInputStream(oldf);
int count=fip.available();
byte[] bytes=new byte[count];
int input=-1;
while((input=fip.read(bytes))!=-1){
fop.write(bytes);
}
fop.flush();
fop.close();
fip.close();
}
static void copydir(String oldpath,String newpath) throws IOException {
File f1=new File(oldpath);
File[] files=f1.listFiles();
for(File ff:files){
if(!ff.isDirectory()){
String newtarget=newpath+File.separator+ff.getName();
copyfile(ff.getAbsolutePath(),newtarget);
}else{
String newtarget=newpath+File.separator+ff.getName();
File newdir=new File(newtarget);
newdir.mkdir();
copydir(oldpath+File.separator+ff.getName(),newpath+File.separator+ff.getName());
}
}
}
static void deletedir(String src){
File srcfile=new File(src);
File[] srcfiles=srcfile.listFiles();
for(File f:srcfiles){
if(f.isFile()){
f.delete();
}else{
deletedir(f.getAbsolutePath());
}
}
srcfile.delete();
}
public static void main(String[] args) throws IOException {
copydir("f:\\java1","f:\\target");
deletedir("f:\\java1");
}
}
|