java复制文件夹及所有子目录和文件
2016-01-12 19:16
399 查看
package text; import java.io.BufferedReader; 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.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; public class fileCopy { public static void main(String[] args) throws IOException { copy("G:/test","E:/test"); System.out.println("复制成功!"); } private static void copy(String f1, String f2) throws IOException { File file1=new File(f1); /* File file2=new File(f2);*/ File[] flist=file1.listFiles(); for (File f : flist) { if(f.isFile()){ copyFile2(f.getPath(),f2+"/"+f.getName()); //调用复制文件的方法 System.out.println("原路径["+f.getPath()+"] 被复制路径["+f2+"/"+f.getName()+"]"); }else if(f.isDirectory()){ copyFile1(f.getPath(),f2+"/"+f.getName()); //调用复制文件夹的方法 System.out.println("原路径["+f.getPath()+"] 被复制路径["+f2+"/"+f.getName()+"]"); } } } /** * 复制文件夹 * @throws IOException */ public static void copyFile1(String f1,String f2) throws IOException{ //创建文件夹 File file=new File(f2); if(!file.exists()){ file.mkdirs(); } copy(f1,f2); } /** * 复制文件 * @throws IOException */ public static void copyFile2(String f1, String f2) throws IOException { try { InputStream input =new FileInputStream(f1); OutputStream output=new FileOutputStream(f2); byte[] bt=new byte[1024]; if((input!=null)&&(output!=null)){ while((input.read(bt))!=(-1)){ output.write(bt,0,bt.length); } } input.close(); output.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
相关文章推荐
- Spring MVC自定义统一异常处理类,并且在控制台中输出错误日志
- 两个字符串中最大的相同的子串(java编写)
- java.lang.IllegalStateException: class utils.filter.ContentFilter is not a javax.servlet.Filter
- JAVA_日期处理
- 重拾编程之路--jeetcode(java)--Add Digits
- Java中的包,类,方法
- 深入理解Java虚拟机 JVM基本框架
- Eclipse乱码怎么办
- Eclipse乱码怎么办
- 深入理解Java虚拟机 垃圾回收器GC
- 深入浅出设计模式(五):7.适配器模式
- java提高篇(十)-----强制类型转换
- Java类加载原理解析
- java增强的for循环详解
- Struts2与Spring整合
- Java基础之集合归总
- Calendar 类的应用
- Spring-MVC配置方法
- JDK 7 中的 Fork/Join 模式 简单入门
- Spring 笔记