【问题标题】:Copying children files of a source to a destination in Java将源的子文件复制到Java中的目标
【发布时间】:2012-12-01 21:42:54
【问题描述】:

我正在尝试制作一个复制目录子目录的程序,但我无法标记所有特定名称,因为它们在每个文件夹中都不同。这是我的代码,但如果源是“C:\src”并且输出是“C:\dst”,它将创建文件夹“C:\dst\src(children files)”,但我想制作“C:\dst(子文件)”。有人可以帮忙吗?

public static void copy(File source, File destination) throws IOException {
    if (source == null) {
        throw new NullPointerException("Null Source");
    }
    if (destination == null) {
        throw new NullPointerException("Null Destination");
    }
    if (source.isDirectory()) {
        copyDirectory(source, destination);
    } else {
        copyFile(source, destination);
    }
}
//converts to location
public static void copyDirectory(File source, File destination) throws IOException {
    copyDirectory(source, destination, null);
}

public static void copyDirectory(File source, File destination, FileFilter filter) throws IOException {
    File nextDirectory = new File(destination, source.getName());
    if (!nextDirectory.exists() && !nextDirectory.mkdirs()) {// create the directory if necessary...
        Object[] filler = {nextDirectory.getAbsolutePath()};
        String message = "Dir Copy Failed";
        throw new IOException(message);
    }
    File[] files = source.listFiles();
    for (int n = 0; n < files.length; ++n) {// and then all the items below the directory...
        if (filter == null || filter.accept(files[n])) {
            if (files[n].isDirectory()) {
                copyDirectory(files[n], nextDirectory, filter);
            } else {
                copyFile(files[n], nextDirectory);
            }
        }
    }
}

public static void copyFile(File source, File destination) throws IOException {
    // what we really want to do is create a file with the same name in that dir
    if (destination.isDirectory()) {
        destination = new File(destination, source.getName());
    }
    FileInputStream input = new FileInputStream(source);
    copyFile(input, destination);
}

public static void copyFile(InputStream input, File destination) throws IOException {
    OutputStream output = null;
    try {
        output = new FileOutputStream(destination);
        byte[] buffer = new byte[1024];
        int bytesRead = input.read(buffer);
        while (bytesRead >= 0) {
            output.write(buffer, 0, bytesRead);
            bytesRead = input.read(buffer);
        }
    } catch (Exception e) {
        //
    } finally {
        input.close();
        output.close();
    }
    input = null;
    output = null;
}

【问题讨论】:

  • 如果您这样做不仅仅是为了锻炼大脑,我应该警告您,您可以在命令行的一行中执行此操作。 cp -r src/* ./dst

标签: java file copy directory copying


【解决方案1】:

试试这个。将文件夹中的整个文件从源复制到目标。

import java.io.*;

public class copydir
{
public static void main(String args[])
{
    File srcFolder = new File("E://Paresh/programs/test");
    File destFolder = new File("D://paresh");

    if(!srcFolder.exists())
    {

          System.out.println("Directory does not exist.");
           //just exit
         System.exit(0);
    }
    else{

           try{
                copyDirectory(srcFolder,destFolder);
                      }
           catch(IOException e)
            {
                    e.printStackTrace();
                    //error, just exit
                        System.exit(0);
                }
        }
    System.out.println("Done");
}

public static void copyDirectory(File src , File target) throws IOException 
{
    if (src.isDirectory()) 
    {
            if (!target.exists()) 
        {
                target.mkdir();
            }

            String[] children = src.list();
            for (int i=0; i<children.length; i++) 
        {
                 copyDirectory(new File(src, children[i]),new File(target, children[i]));
            }
    }
    // if Directory exists then only files copy
    else 
    {

        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(target);

        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) 
        {
                    out.write(buf, 0, len);
        }
        in.close();
        out.close();
        }
   }    

}

【讨论】:

    【解决方案2】:

    您可以使用 commons-io 库在一行中完成所有操作:

    FileUtils.copyDirectory(src, dest);
    

    见: http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html#copyDirectory%28java.io.File,%20java.io.File%29

    jar 文件:http://mvnrepository.com/artifact/commons-io/commons-io/2.4

    【讨论】:

    • 您能否一直指望目标系统上安装了 commons-io,还是必须将其包含在您的项目中?
    • commons-io 是一个第三方库。您必须将其包含在您的项目中。
    【解决方案3】:

    替换

    if (source.isDirectory()) {
        copyDirectory(source, destination);
    } else {
        copyFile(source, destination);
    }
    

    if (source.isDirectory()) {
        for (File child : source.listFiles()) {
            if (child.isDirectory()) {
                copyDirectory(child, destination);
            } else {
                copyFile(child, destination);
            }
        }
    } else {
        copyFile(source, destination);
    }
    

    【讨论】:

      【解决方案4】:

      使用 getParentFile() 获取父目录:

      if (source.isDirectory()) {
          copyDirectory(source, destination.getParentFile());
      } else {
          copyFile(source, destination.getParentFile());
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-30
        • 1970-01-01
        • 1970-01-01
        • 2017-03-31
        • 1970-01-01
        相关资源
        最近更新 更多