复制文件夹思路是:先实现文件的复制,然后遍历文件夹下的文件进行复制
代码如下:
- 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")
- //文件的复制
- 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){
- buffer.flip();//准备写入,防止其他读取,锁住文件
- out.write(buffer);
- 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();
- }
- }
复制代码 |
|