文件夹的拷贝和移动

实现文件夹的拷贝和移动

复杂样例
文件夹的深度无法提前预知,所以这里采用递归调用的方式进行操作

public class Test1 {
    
     
    private static String source; 
    private static String target; 
    public static void main(String[] args) throws IOException {
    
     
        source="C:\\aaa"; 
        target="c:\\ddd"; 
        File ff=new File(source); 
        copy(ff); 
    }
    public static void copy(File file)throws IOException{
    
     
        if(file!=null && file.exists()) {
    
    
            if(file.isDirectory()) {
    
     
                String path=file.getAbsolutePath(); 
                String newPath=path.replace(source, target); 
                File tmp=new File(newPath); 
                if(!tmp.exists())
                    tmp.mkdirs(); 
                File[] fs=file.listFiles(); 
                if(fs!=null && fs.length>0)
                    for(File temp:fs)
                        copy(temp); 
            }else if(file.isFile()) {
    
     
                String path=file.getAbsolutePath(); 
                String newPath=path.replace(source, target); 
                try(InputStream is=new FileInputStream(file); 
                    OutputStream os=new FileOutputStream(newPath); ){
    
     
                    byte[] buffer=new byte[8192]; 
                    int len=0; 
                    while((len=is.read(buffer))>0) 
                        os.write(buffer,0,len); 
                } 
            } 
        } 
    } 
}

猜你喜欢

转载自blog.csdn.net/qq_43480434/article/details/113194920
今日推荐