首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Java中将文件从一个目录复制到另一个目录

在Java中将文件从一个目录复制到另一个目录
EN

Stack Overflow用户
提问于 2009-07-17 23:38:43
回答 23查看 499.6K关注 0票数 175

我想使用Java将文件从一个目录复制到另一个目录(子目录)。我有一个目录dir,里面有文本文件。我迭代了dir中的前20个文件,并希望将它们复制到dir目录中的另一个目录中,该目录是我在迭代之前创建的。在代码中,我希望将review (表示第i个文本文件或评论)复制到trainingDir。我该怎么做呢?似乎没有这样的函数(或者我找不到)。谢谢。

代码语言:javascript
复制
boolean success = false;
File[] reviews = dir.listFiles();
String trainingDir = dir.getAbsolutePath() + "/trainingData";
File trDir = new File(trainingDir);
success = trDir.mkdir();
for(int i = 1; i <= 20; i++) {
    File review = reviews[i];

}
EN

回答 23

Stack Overflow用户

发布于 2009-07-18 03:35:54

现在,这应该可以解决您的问题

代码语言:javascript
复制
File source = new File("H:\\work-temp\\file");
File dest = new File("H:\\work-temp\\file2");
try {
    FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
    e.printStackTrace();
}

apache commons-io库中的FileUtils类,从1.2版开始可用。

使用第三方工具而不是自己编写所有的实用程序似乎是一个更好的想法。它可以节省时间和其他宝贵的资源。

票数 186
EN

Stack Overflow用户

发布于 2009-07-18 00:03:05

下面来自Java Tips的示例相当简单。从那以后,我转而使用Groovy来处理文件系统--更简单、更优雅。但这是我过去用过的Java提示。它缺乏健壮的异常处理,这是使它变得简单可靠所必需的。

代码语言:javascript
复制
 public void copyDirectory(File sourceLocation , File targetLocation)
    throws IOException {

        if (sourceLocation.isDirectory()) {
            if (!targetLocation.exists()) {
                targetLocation.mkdir();
            }

            String[] children = sourceLocation.list();
            for (int i=0; i<children.length; i++) {
                copyDirectory(new File(sourceLocation, children[i]),
                        new File(targetLocation, children[i]));
            }
        } else {

            InputStream in = new FileInputStream(sourceLocation);
            OutputStream out = new FileOutputStream(targetLocation);

            // 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();
        }
    }
票数 29
EN

Stack Overflow用户

发布于 2009-07-17 23:52:57

如果你想复制一个文件而不是移动它,你可以像这样编写代码。

代码语言:javascript
复制
private static void copyFile(File sourceFile, File destFile)
        throws IOException {
    if (!sourceFile.exists()) {
        return;
    }
    if (!destFile.exists()) {
        destFile.createNewFile();
    }
    FileChannel source = null;
    FileChannel destination = null;
    source = new FileInputStream(sourceFile).getChannel();
    destination = new FileOutputStream(destFile).getChannel();
    if (destination != null && source != null) {
        destination.transferFrom(source, 0, source.size());
    }
    if (source != null) {
        source.close();
    }
    if (destination != null) {
        destination.close();
    }

}
票数 23
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1146153

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档