IO—文件夹拷贝

文件夹复制

package com.cn.dark;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

/**
 * 使用文件输入、输出流实现文件拷贝
 * @author DARK
 *
 */
public class CopyFile {
	
	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
        System.out.println("请输入源目录:");
        String sourcePath = sc.nextLine();
        System.out.println("请输入新目录:");
        String path = sc.nextLine();
        boolean flag=true;//控制创建拷贝文件夹
        //String sourcePath = "D://aa";
        //String path = "D://bb";
        
        copyDir(sourcePath, path,flag);
		
	}
	//文件拷贝
	public static void copyFile(String srcPath,String destPath) {
		//文件字节输入流
		//1、创建源
		File src=new File(srcPath);//源头
		File dest=new File(destPath);//目的地
		//2、选择流
		InputStream is=null;
		OutputStream os=null;
		
		try {
				is=new  FileInputStream(src);
				os=new FileOutputStream(dest);
				
				//3、操作(分段读取)
				byte[] flush=new byte[1024*10];//缓冲容器
				int len=-1;
				
				while((len=is.read(flush))!=-1) {//read返回的是缓存容器中存储字节的个数
//					//字节数组-->字符串(解码)
//					String str=new String(flush,0,len);
//					byte[] datas=str.getBytes();//字符串-->字节数组;编码
					os.write(flush,0,len);
				}
				os.flush();//刷新,防止驻留在缓存
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				//4、释放资源 分别关闭 先打开的后关闭
				if(null!=os) {
					try {
						os.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
				if(null!=is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}				
			}
		}
	}
	//文件夹拷贝
	public static void copyDir(String oldPath, String newPath,boolean flag) throws IOException {
        	File file = new File(oldPath);
        	if(flag) {
        		newPath=newPath+"/"+file.getName();
        		new File(newPath).mkdir();//拷贝根文件夹
        		flag=false;
        	}
        	//文件名称列表
            String[] filePath = file.list();
            
            if (!(new File(newPath)).exists()) {
                     (new File(newPath)).mkdir();
                 }
                 
                 for (int i = 0; i <filePath.length; i++) {
                	 //递归 拷贝文件夹
                     if ((new File(oldPath + file.separator + filePath[i])).isDirectory()) {
                         copyDir(oldPath  + file.separator  + filePath[i], newPath  + file.separator + filePath[i],flag);
                     }
                     //文件直接拷贝
                     if (new File(oldPath  + file.separator + filePath[i]).isFile()) {
                         copyFile(oldPath + file.separator + filePath[i], newPath + file.separator + filePath[i]);
                     }
                    
                 }
  
    }
}
posted @ 2022-04-08 23:24  FireCode  阅读(54)  评论(0)    收藏  举报