复制文件或目录到指定目录下

本文提供了一个Java程序示例,演示了如何复制文件和目录。通过使用File类和输入输出流,程序实现了文件及目录从源位置到目标位置的完整复制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

记录自己的学习过程..

package what;
import java.io.*;
class CopyFiles
{
	private String pathFrom;  //被复制文件或目录的路径名
	private String pathTo;    //指定目录的路径名
	private String p;         //复制后文件或目录的新路径名
	private int index;        //被复制文件或目录名在原路径名中的索引
	public void copy(String pathF,String pathT)
	{
		this.pathFrom=pathF;
		this.pathTo=pathT;
		index=pathFrom.lastIndexOf("\\");
		if(new File(pathFrom).isDirectory())
			this.copyD(pathFrom); 
		else
			this.copyF(pathFrom); 
	}
	public void copyF(String path)     //复制文件
	{
		p=pathTo+File.separator+path.substring(index);
		try(
				FileInputStream fis=new FileInputStream(path);
				FileOutputStream fos=new FileOutputStream(p))
		{
			byte[] bbuf=new byte[512];
			int hasRead=0;
			while((hasRead=fis.read(bbuf))>0)
			{
				fos.write(bbuf,0,hasRead);
			}
		}
		catch(IOException ioe)
		{
			ioe.printStackTrace();
		}
	}
	public void copyD(String path)    //复制目录
	{
		p=pathTo+path.substring(index);
		new File(p).mkdir();          //建立新目录
		String[] fileList=new File(path).list(); //获得File对象下的文件名或目录名
		for(String f:fileList)  
		{
			f=path+File.separator+f;   //须将f改为绝对路径名,以判断是目录或文件
			if(new File(f).isDirectory())
				this.copyD(f);        
			else
				this.copyF(f); 
		}
	}
}
public class Example
{
	public static void main(String[] args)throws Exception
	{   // 依次输入原文件或目录、指定目录的路径名
		new CopyFiles().copy("E:\\编程程序\\what\\bin\\what\\Example.class","E:\\编程程序\\what复制件");
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值