分析:
有了文件复制到文件夹的方法,便可以通过遍历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();
}
}