java 拷贝目录

package 拷贝目录;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyTest03 {
     

	public static void main(String[] args) {
     
		// TODO Auto-generated method stub

		//源
		File srcFile =new File("D:\\拷贝");
		//拷贝目标
		File destFile =new File("D:\\拷贝目录");
		
		//调用拷贝方法
		copyDir(srcFile,destFile);
	}
	
	private static void copyDir(File srcFile,File destFile) {
     
		 if(srcFile.isFile()) {
      //如果是文本了,开始拷贝  
			 
			 FileInputStream in =null;
			 FileOutputStream out =null;
			 
			 try {
     
				in =new FileInputStream(srcFile);
				String endPath=destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\"+srcFile.getAbsolutePath().substring(3);
				out =new FileOutputStream(endPath);
				//文本的复制
				byte[] bytes= new byte[1024*1024] ;//1M
				int readCount =0;
				while((readCount=in.read(bytes))!=-1) {
     
					out.write(bytes);
				}
				//刷新
				out.flush();
			 } catch (FileNotFoundException e) {
     
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
     
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
     
				if (in != null) {
     
					try {
     
						in.close();
					} catch (IOException e) {
     
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if (out != null) {
     
					try {
     
						out.close();
					} catch (IOException e) {
     
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			 
			 return;
		 }
		
		 //如果是目录 递归到文本
		File[] files =srcFile.listFiles();
		for (File file : files) {
     
			if(file.isDirectory()) {
      //如果是目录
				//源目录的绝对路径
				String srcDir= file.getAbsolutePath();
				//拷贝目标的绝对路径
				String destDir=destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\"+srcDir.substring(3);
				//新建目录
				File newFile = new File(destDir);
				newFile.mkdirs();
			}
			//递归
			copyDir(file,destFile);
		}

	}
	
}

你可能感兴趣的:(文件,java)