- package cn.itcast.test;
- import java.io.*;
- public class Copy {
-
- public static void main(String[] args)throws Exception
- {
- /*
- * ①首先你要输入一个c盘的文件夹,一直到你输入正确为止
- * */
- System.out.println("请输入C盘的一个文件夹目录(悠着点,文件夹太大时间长):");
- BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
- String olddir=null;
- File cfile=null;
- while((olddir=bufr.readLine())!=null)
- {
-
- cfile=new File(olddir);
-
-
- if(cfile.isDirectory())
- {
- File dfile=changeDir(cfile);
- dfile.mkdir();
- break;
- }
- else
- System.out.println("该路径不存在,请重新输入:");
- }
- /*
- * ②调用copy函数,将C盘文件夹复制到D盘
- * */
- copy(cfile);
- }
-
- public static void copy(File dir)throws Exception
- {
- File[] files=dir.listFiles();
-
- for(int i=0;i<files.length;i++)
- {
- if(files[i].isDirectory())
- {
- //在D盘创建文件夹
- File newfile=changeDir(files[i]);
- newfile.mkdir();
- copy(files[i]);
-
- }else{
-
- //把文件复制到D盘相应的路径下
- File newfile=changeDir(files[i]);
-
- BufferedReader bufIn=
- new BufferedReader(new InputStreamReader(new FileInputStream(files[i])));
- PrintWriter pw=
- new PrintWriter(new FileOutputStream(newfile));
-
- String line=null;
-
- while((line=bufIn.readLine())!=null)
- {
- pw.println(line);
- }
- bufIn.close();
- pw.close();
-
- }
- }
- }
- //此函数负责将C盘的路径转换成D盘相应的路径
- public static File changeDir(File oldfile)throws Exception
- {
- String olddir=oldfile.getCanonicalPath();
-
- char[] array=olddir.toCharArray();
-
- array[0]='D';
-
- String newdir=new String(array);
- File newfile=new File(newdir);
-
- return newfile;
- }
- }
复制代码 请大家多多指点
|