zoukankan      html  css  js  c++  java
  • Java实现文件夹的复制(包括子文件夹与文件)

    package com.test.file;
    
    import sun.java2d.pipe.BufferedBufImgOps;
    
    import java.io.*;
    
    public class RecursionDir {
    
            //copy directory and files
            public static void copyDir(String oldPath,String newPath) throws Exception{
                File src = new File(oldPath);
                File tar = new File(newPath);
                File[] fs = src.listFiles();
    
                //create target directory
                if(!tar.exists()){
                    tar.mkdirs();
                }
    
                //get current dir's files and dirs
                for(File f:fs){
                    if(f.isFile()){
                        //copy file
                        copyFile(f,new File(newPath+"//"+f.getName()));
                    }else if(f.isDirectory()){
                        //recursion
                        copyDir(f.getPath(),newPath+"//"+f.getName());
                    }
                }
            }
    
            //copy files
            public static void copyFile(File src,File tar) throws Exception{
                //create inputStream buffer
                FileInputStream fis = new FileInputStream(src);
                BufferedInputStream bif = new BufferedInputStream(fis);
    
                //create outputStream buffer
                FileOutputStream fos = new FileOutputStream(tar);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
    
                //buffer array
                byte[] bs = new byte[1024];
                int len;
                while((len=bif.read(bs))!=-1){
                    bos.write(bs,0,len);
                }
                bos.flush();
    
    
                //close stream
                fis.close();
                fos.close();
                bif.close();
                bos.close();
    
            }
    
    }
    

      

  • 相关阅读:
    强制重置管理员密码
    Leetcode-Wildcard Matching
    Leetcode-Merge Intervals
    Leetcode-Insert Interval
    Leetcode-Recover BST
    Leetcode-Validate BST
    Leetcode-Same Tree
    Leetcode-Symmetric Tree
    Leetcode-Construct Binary Tree from inorder and postorder travesal
    Leetcode-Binary Tree Level Order Traversal II
  • 原文地址:https://www.cnblogs.com/MyBlog-/p/7281871.html
Copyright © 2011-2022 走看看