io流实现复制某文件夹的全部内容到其他文件夹中

 

//G:\\javaPro 目录下所有文件复制到F:\\javaPro

import java.io.*;
public class CopyTest01 
{
    public static void main(String[] args) 
    {    String sourceDir="G:\\javaPro";
        File sd=new File(sourceDir);
        CopyTest01 ct=new CopyTest01();
        ct.copy(sd);

//mkdir与mkdirs的区别? String sourceDir2="F:\\JavaSE_01\\资料及源代码\\资料及源代码\\代码练习\\chapter08_io\\CopyTest01.java"; File sd2=new File(sourceDir2); File parentFile2=sd2.getParentFile(); parentFile2.mkdir(); /*在"F:\\JavaSE_01\\资料及源代码\\资料及源代码\\代码练习\\chapter08_io\\CopyTest01.java";中 只创建chapter08_io目录,在"F:\\JavaSE_01\\资料及源代码\\资料及源代码\\代码练习\\"目录已经存在时,可以 这么用 parentFile2.mkdirs(); 直接创建 F:\\JavaSE_01\\资料及源代码\\资料及源代码\\代码练习\\chapter08_io\\目录*/
} public void copy(File f){ if(f.isFile()){ String filePath=f.getAbsolutePath();//获取文件绝对路径 String newPath="F"+filePath.substring(1);//生成新的文件路径 File parentFile = new File(newPath).getParentFile(); if(!parentFile.exists()){ parentFile.mkdirs(); } FileInputStream fis=null; FileOutputStream fos=null; try{ fis=new FileInputStream(filePath); fos=new FileOutputStream(newPath); byte[] bytes=new byte[102400];//100kb int t; while((t=fis.read(bytes))!=-1){ fos.write(bytes,0,t); } fos.flush(); }catch(Exception e){ e.printStackTrace(); }finally{ if(fis!=null){ try{ fis.close(); }catch(Exception e){ e.printStackTrace(); } } if(fos!=null){ try{ fis.close(); }catch(Exception e){ e.printStackTrace(); } } } }//if else{ File[] files=f.listFiles(); for(File file:files){ copy(file); } } } }

 

posted @ 2017-08-17 22:32  Allen101  阅读(689)  评论(0编辑  收藏  举报