模拟copy命令,接收源文件路径和目标文件路径,实现文件或文件夹拷贝操作

package learning;

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

import javax.xml.crypto.Data;

public class IOStreamPractice {
//模拟copy命令,接收源文件路径和目标文件路径,实现文件或文件夹拷贝操作
//需求分析:各种文件都有,用字节流;大文件的拷贝
//思路:采用部分拷贝,拷贝一部分就输出一部分
	public static void main(String[] args) throws Exception {
		Scanner sc=new Scanner(System.in);
		String srcPath=sc.next();
		String desPath=sc.next();
		File srcFile=new File(srcPath);
		File desFile=new File(desPath);
		
		boolean b=FileUtil.copyImpl(srcFile,desFile);
		System.out.println(b? "拷贝成功":"拷贝失败,请排查原因");
	}	
	
}

class FileUtil {
	public static boolean copyImpl(File srcFile,File desFile) throws Exception{
		if(!srcFile.exists())	return false;		//处理特殊情况
		if(!desFile.getParentFile().exists())	desFile.getParentFile().mkdirs();
		
		if(srcFile.isFile()) {		//区分拷贝的是普通文件,还是目录文件
			return FileUtil.copyNormal(srcFile,desFile);
		}
		else {
			return FileUtil.copyDir(srcFile,srcFile,desFile);
		}
	}

	private static boolean copyNormal(File srcFile, File desFile) throws Exception{
		//被copyDir调用时父目录可能不存在
		if(!desFile.getParentFile().exists())	desFile.getParentFile().mkdirs();
		InputStream input=new FileInputStream(srcFile);
		OutputStream output=new FileOutputStream(desFile);
		byte[] buffer=new byte[1024];		//每趟最多拷贝1024字节
		int len=0;
		while( (len=input.read(buffer))!=-1 ) {		//一直把文件读完为止
			output.write(buffer,0,len);
		}
		return true;
	}
	
	private static boolean copyDir(File File,File srcFile, File desFile) throws Exception{
		if(File.isDirectory()) {		//是目录,则递归拷贝
			File[] subFiles=File.listFiles();
			if(subFiles!=null) {
				for(int i=0;i<subFiles.length;i++)	copyDir(subFiles[i], srcFile, desFile);
			}
		}
		else {
			//重新构建路径名
			String oldPath=File.getPath().replace(srcFile.getPath()+File.separator,"");
			File newFile=new File(desFile.getPath(), oldPath);
			copyNormal(File, newFile);
		}
		
		return true;
	}
}
posted @   fighterk  阅读(230)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示