我的代码如下,已测试成功,谢谢
- package cn.itcast.heima;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- public class CopyFile {
- private static BufferedReader br = null;
- private static PrintWriter pw = null;
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- //指定路径
- String srcPath = "C:/";
- String desPath = "D:/";
- String Path = desPath + srcPath.substring((srcPath.indexOf("/") + 1));
- File file = new File(srcPath);
- //列出源路径下的文件和文件夹
- File[] files = file.listFiles();
- traversal(files,Path);
- }
-
- //用于遍历整个文件夹
- public static void traversal(File[] files,String Path){
- for(File file: files){
- //若是文件夹则在D盘创建文件夹,并进行递归调用
- if(file.isDirectory()){
- String newPath = Path + "/" + file.getName();
- File f = new File(newPath);
- f.mkdirs();
- traversal(file.listFiles(),Path + "/" + file.getName());
- }else{
- //若是文件则复制到D盘相应目录
- copyFile(file,Path);
- }
- }
- }
-
- //用于拷贝文件
- public static void copyFile(File file,String Path){
- try {
- br = new BufferedReader(new FileReader(file.getAbsoluteFile()));
- System.out.println(Path + file.getName());
- File f = new File(Path + "/" + file.getName());
- pw = new PrintWriter(f);
- String s = null;
- while((s = br.readLine()) != null){
- pw.println(s);
- }
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally{
- try {
- if(br != null)
- br.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- if(pw != null)
- pw.close();
- }
-
- }
- }
复制代码 |