文件夹的复制

来源:互联网 发布:非农数据股市 编辑:程序博客网 时间:2024/05/29 13:19

IO文件流只能读取文件的内容,复制文件夹就是多个文件复制的组合。难点在于找到出这个文件夹下的所有文件,如果这个文件夹下面有子文件,还需要找出这个子文件夹下面的所有文件,这就需要用到递归。

package io.file;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;import java.util.Scanner;public class CopyDir {public static void main(String[] args) {/*Scanner scanner=new Scanner(System.in);String oldDir=scanner.nextLine();String newDir=scanner.nextLine();*/File oldFile=new File("F:"+File.separator+"music");File newFile=new File("F:"+File.separator+"music1");listAllFiles(oldFile,newFile);}private static void listAllFiles(File oldDir,File newDir) {newDir.mkdirs();File[] files=oldDir.listFiles();for(int i=0;i<files.length;i++){File fileTemp=files[i];if(fileTemp.isFile()){File file1=new File(oldDir+File.separator+fileTemp.getName());File file2=new File(newDir+File.separator+fileTemp.getName());copy(file1,file2);System.out.println(file1.getAbsolutePath());System.out.println(file2.getAbsolutePath());}else if(fileTemp.isDirectory()){File file1=new File(oldDir+File.separator+fileTemp.getName());File file2=new File(newDir+File.separator+fileTemp.getName());file2.mkdirs();listAllFiles(file1, file2);}}}private static void copy(File file1, File file2) {//file1的内容读出来写到file2try {InputStream in=new FileInputStream(file1);byte[] b=new byte[in.available()];in.read(b);OutputStream out=new FileOutputStream(file2);out.write(b);out.close();in.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


原创粉丝点击