java 文件拷贝

1.拷贝文件

 

 private void copyFile(File source, File target) {
       FileInputStream inFile = null;   
        FileOutputStream outFile = null;   
        try {   
            inFile = new FileInputStream(source);   
            outFile = new FileOutputStream(target);   
            byte[] buffer = new byte[1024];   
            int i = 0;   
            while ((i = inFile.read(buffer)) != -1) {   
                outFile.write(buffer, 0, i);   
            }   
            inFile.close();   
            outFile.close();   
        } catch (FileNotFoundException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        } finally {   
            try {   
                if (inFile != null) {   
                    inFile.close();   
                }   
                if (outFile != null) {   
                    outFile.close();   
                }   
            } catch (IOException e) {   
                e.printStackTrace();   
            }   
        }   
    }   

 

 2.拷贝文件目录处理

 // 处理目录   
    public void copyDict(File source, File target) {   
        File[] file = source.listFiles();// 得到源文件下的文件项目   
        if(!target.exists())   
        {   
        	target.mkdirs();   //创建根目录
        } 
        for (int i = 0; i < file.length; i++) {   
            if (file[i].isDirectory()) {// 判断是文件夹   
                File sourceDemo = new File(source.getAbsolutePath() + "/"  
                        + file[i].getName());   
                File destDemo = new File(target.getAbsolutePath() + "/"  
                        + file[i].getName());   
                destDemo.mkdirs();// 建立文件夹   
                this.copyDict(sourceDemo, destDemo);   
            }  
            if (file[i].isFile()) {//判断是文件   
                File sourceDemo = new File(source.getAbsolutePath() + "/"  
                        + file[i].getName());   
                File destDemo = new File(target.getAbsolutePath() + "/"  
                        + file[i].getName());   
                this.copyFile(sourceDemo, destDemo);   
            } 
        }// end copyDict   
  
    }   

 

3.测试拷贝方法

 

 public static void main(String[] args) {
  // TODO Auto-generated method stub
        FileUtil fileUtil=new FileUtil();
        File srcDir = new File("E://100");   
        File targetDir = new File("E://110");   
        fileUtil.copyDict(srcDir,targetDir);   
 }

 

你可能感兴趣的:(java)