黑马程序员————文件夹复制到文件夹

分析:

有了文件复制到文件夹的方法,便可以通过遍历sourceFile中的文件将文件夹复制到文件夹

结论:

通过

String[] sF=new File(sourceD).list()
和<pre name="code" class="html">for (int i = 0; i < sF.length; i++)
两个语句实现对源文件的遍历

 

下面是实现代码:

package sample;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

class CopyFile{
	protected File sourceF;
	protected File targetF;
	CopyFile(File sourceF,File targetF){
		this.sourceF=sourceF;
		this.targetF=targetF;
	}
	@SuppressWarnings("resource")
<span style="white-space:pre">	</span>//文件复制到文件
	public  void Copy() throws IOException{
		if(targetF.isDirectory())
		{ 
			targetF.mkdirs();
			//在目标文件夹中建立和目标文件同名的文件
			targetF=new File(targetF.getAbsolutePath()+"\\"+sourceF.getName());
			
		}
		FileChannel in = new FileInputStream(sourceF).getChannel();      
		FileChannel out = new FileOutputStream(targetF).getChannel();  
        ByteBuffer buffer = ByteBuffer.allocate(1024);//设定缓冲区  
        while(in.read(buffer) != -1){  
        <span style="font-family: Arial, Helvetica, sans-serif;">//准备写入,防止其他读取,锁住文件</span><span style="font-family: Arial, Helvetica, sans-serif;">    </span>

<span style="white-space:pre">	</span>buffer.flip();  
            out.write(buffer);
<span style="white-space:pre"></span><pre name="code" class="html">       //准备读取。将缓冲区清理完毕,移动文件内部指针
buffer.clear(); } in.close(); out.close();}}class CopyDirectory {private String sourceD;private String targetD;CopyDirectory(String sourceD, String targetD) {this.sourceD=sourceD;this.targetD=targetD;}

 
       //文件夹复制到文件夹
	public void Copy() throws IOException{
		//System.out.println(sourceD);
		String[] sF=new File(sourceD).list();
		String sTemp=targetD+"\\"+new File(sourceD).getName();//在目标文件夹中建立和源文件同名文件夹
		File tF=new File(sTemp);
		tF.mkdirs();
		for (int i = 0; i < sF.length; i++){
			if(new File(sourceD+"\\"+sF[i]).isFile())
			{
				System.out.println(sourceD+"\\"+sF[i]+2);
				File sourceF=new File(sourceD+"\\"+sF[i]);
				File targetF=tF;
				new CopyFile(sourceF,targetF).Copy();
			}
			else if(new File(sourceD+"\\"+sF[i]).isDirectory())
			{
				sourceD=sourceD+"\\"+sF[i];
				System.out.println(sourceD+1);
				targetD=sTemp;
				new CopyDirectory(sourceD,targetD).Copy();
			}
		}
		
		//File[] file=new File(sourceD).listFiles();
		
	}
}
public class Sample2 {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
         String sourceD="C:\\新建文件夹";
         String targetD="E:\\新建文件夹";
         new CopyDirectory(sourceD,targetD).Copy();
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值