在Java中手动复制目录和文件夹

时间:2016-01-07 23:28:52

标签: java directory

我的任务是手动将目录和文件夹从源复制到目标。我的问题是,如果用户输入源代码C:\\folder1和目标C:\\folderK(假设我们有这种情况) - >(见下文)。

C:\
 folder1
    B.txt
    folder2
       A.txt



C:\
    folderK

我希望我的结果是:

C:\
 folderK
     folder1
       B.txt
       folder2
          A.txt

如果用户为来源C\\folder1和目标C:\\folderK\\folderD输入类似内容,则结果必须为:

C:\
     folderK
         folderD   !!!(name of folder1 is changed to folderD)
           B.txt
           folder2
              A.txt

到目前为止,这是我的代码:

void copy(File source, File destination) throws IOException {

            if(source.isDirectory()){
                if(!destination.exists()){
                   destination.mkdir();
                }

                for (String file : source.list()) {
                   System.out.println(file);
                   copy(new File(source, file), new File(destination, file));
                }
            } else {
                    BufferedReader br = new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(source)), "UTF-8"));
                    Writer bw = new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(destination)), "UTF-8"));

                    while(true) {
                    String line = br.readLine(); if(line == null) break;
                    bw.write(line);
                    }

                    br.close();
                    bw.close();
            }       
}

我的代码无法正常显示。它接下来做了:

C:\
  folderK
    B.txt
    folder2
      A.txt

我应该在代码中添加什么,以便它能够正常工作(如开头所述)

1 个答案:

答案 0 :(得分:1)

我会添加一个布尔参数来指示是否必须在目标中创建最后一个源文件夹,如下所示:

void copy(File source, File destination, boolean folderCreate) throws IOException {
        if(source.isDirectory()){
            File dest;
            if(folderCreate)
                dest=new File(destination,source.getName());
            else
                dest=destination;

            if(!dest.exists()){
               dest.mkdir();
            }

            for (String file : source.list()) {
               System.out.println(file);
               copy(new File(source, file), new File(dest, file), false);
            }
        } else {
                BufferedReader br = new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(source)), "UTF-8"));
                Writer bw = new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(destination)), "UTF-8"));

                while(true) {
                String line = br.readLine(); if(line == null) break;
                bw.write(line);
                }

                br.close();
                bw.close();
        }       
}