JAVA实现文件夹的复制
思路分析代码展示思路分析
实现文件夹的复制,需要考虑到文件夹和文件的差别。如果是文件,则可以直接利用java中io流进行文件的复制,如果是文件夹,则需要考虑源文件夹的路径,在目标位置创建相应文件夹,进行递归处理。
代码展示
package com.java.study;import java.util.*;import java.io.*;public class Test {private String src;private String target;public Test(String src, String target) {this.src = src;this.target = target;}public String getSrc() {return src;}public void setSrc(String src) {this.src = src;}public String getTarget() {return target;}public void setTarget(String target) {this.target = target;}//复制文件,后续大家可以考虑缓冲问题,减少io次数,从而提高效率static void copyfile(String oldfile,String newfile) throws IOException {File oldf=new File(oldfile);FileOutputStream fop=new FileOutputStream(new File(newfile));FileInputStream fip=new FileInputStream(oldf);int count=fip.available();byte[] bytes=new byte[count];int input=-1;while((input=fip.read(bytes))!=-1){fop.write(bytes);}fop.flush();fop.close();fip.close();}//复制文件夹static void copydir(String oldpath,String newpath) throws IOException {File f1=new File(oldpath);File[] files=f1.listFiles();for(File ff:files){if(!ff.isDirectory()){//如果是文件,直接调用上面文件复制方法进行复制String newtarget=newpath+File.separator+ff.getName();copyfile(ff.getAbsolutePath(),newtarget);}else{//如果是文件夹,运用递归进行文件夹的复制String newtarget=newpath+File.separator+ff.getName();File newdir=new File(newtarget);newdir.mkdir();copydir(oldpath+File.separator+ff.getName(),newpath+File.separator+ff.getName());}}}public static void main(String[] args) throws IOException {copydir("f:\\java1","f:\\target");}}