package com.xm.xiong; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class TwoFile { /** * @param args */ public static void main(String[] args) { //原目录 File file = new File("D:/ebook"); try { //复制输出目录 getFileLst(file,"D:/ee"); } catch (IOException e) { e.printStackTrace(); } } /** *得到当前文件夹下的文件列表 *dir :原目录 *otherpath:复制目录 */ static File globle = null; public static void getFileLst(File dir,String otherpath) throws IOException { if(dir.exists() && dir.isDirectory()) { //如果目标目录不存在,传目标目录 File otherpathf = new File(otherpath); if(!otherpathf.exists()) { otherpathf.mkdirs(); } String[] files = dir.list(); for(int i = 0;i<files.length;i++) { globle = new File(dir.getPath()+"/"+files[i]); //如果是目录创建目录并递归 if(globle.exists() && globle.isDirectory()) { //创建目录 File newdir = new File(otherpath+"/"+files[i]); newdir.mkdir(); //递归 getFileLst(globle,otherpath+"/"+files[i]); } else { //复制文件 copy(globle,new File(otherpath+"/"+files[i])); } } } } /** * 复制目录 * old:源文件 * newfile:复制文件 * */ public static void copy(File old,File newfile) throws IOException{ InputStream in = null; OutputStream out = null; try { in = new FileInputStream(old); out = new FileOutputStream(newfile); int len = 0; byte[] b = new byte[1024]; while((len=in.read(b))>-1) { out.write(b, 0, len); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if(in!=null) { in.close(); } if(out!=null) { out.close(); } } } }