尚学堂 JAVA300集 第十章IO技术 video175 IO_文件拷贝---拓展:copy 文件夹及文件夹下内容到目标文件夹下

video175 IO_文件拷贝—拓展:copy 文件夹及文件夹下内容到目标文件夹下

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;

/**
 * copy 该文件夹及文件夹下内容到目标文件夹下
 * @author lei.ai
 *
 */
public class IOCopy03extend {

	public static void main(String[] args) throws IOException {
		copytodir("D:\\code\\Pro10\\test","D:\\code\\Pro10\\copytest");
		
	}
		
	
	private static void copytodir(String sourcepath,String destpath) throws IOException {
		// TODO Auto-generated method stub
		File sorce = new File(sourcepath);	//源文件
		File dest = new File(destpath);
		//创建目标文件夹
		dest.mkdirs();		//如果目标文件夹已存在,则创建失败
		
		//将源文件名与目标路径相结合,存到buffd中
		File buffd = new File(dest.getAbsolutePath(),sorce.getName());
				
		if (sorce!=null && sorce.exists()) {
			
			if (sorce.isFile()) {	//如果是文件,在目标目录中创建该文件,并将内容复制
				buffd.createNewFile();
				copyfile(sorce.getAbsolutePath(), buffd.getAbsolutePath());
			}else {		//如果是文件夹,则递归调用
				for(File s:sorce.listFiles()) {
					File buffs = new File(sorce.getAbsolutePath(),s.getName());		
					copytodir(buffs.getAbsolutePath(),buffd.getAbsolutePath());
				}
			}
		}
	}
	
	
	
	
	
	
	
	private static void copyfile(String sourcepath,String destpath) {
		//1.创建源
		File sorce = new File(sourcepath);	//源文件
		File dest = new File(destpath);		//目标文件
		//2.选择流
		InputStream is = null;
		OutputStream os = null;
		
		try {
			is = new FileInputStream(sorce);
			os = new FileOutputStream(dest);
			//3.操作
			//分段读取
			byte[] flush = new byte[1024];
			int len;	//定义解码接收长度
			while ((len=is.read(flush))!=-1) {
				
				os.write(flush, 0, len);
				/*
				String st = new String(flush, 0, len);	//编码
				byte[] temp = st.getBytes();			//解码
				os.write(temp, 0, temp.length);			//写入
				*/
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {	//4、释放资源 分别关闭 先打开的后关闭
			if (os!=null) {
				try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			if(is!=null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}

	}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值