用Java将文件从一个目录复制到另一个目录 [英] Copying files from one directory to another in Java

查看:53
本文介绍了用Java将文件从一个目录复制到另一个目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Java 将文件从一个目录复制到另一个(子目录).我有一个带有文本文件的目录 dir.我遍历 dir 中的前 20 个文件,并希望将它们复制到 dir 目录中的另一个目录,该目录是我在迭代之前创建的.在代码中,我想将review(代表第i个文本文件或review)复制到trainingDir.我怎样才能做到这一点?似乎没有这样的功能(或者我找不到).谢谢.

I want to copy files from one directory to another (subdirectory) using Java. I have a directory, dir, with text files. I iterate over the first 20 files in dir, and want to copy them to another directory in the dir directory, which I have created right before the iteration. In the code, I want to copy the review (which represents the ith text file or review) to trainingDir. How can I do this? There seems not to be such a function (or I couldn't find). Thank you.

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];

}

推荐答案

现在应该可以解决你的问题

For now this should solve your problem

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();
}

FileUtils 类来自 apache commons-io 库,自版本起可用1.2.

FileUtils class from apache commons-io library, available since version 1.2.

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

Using third party tools instead of writing all utilities by ourself seems to be a better idea. It can save time and other valuable resources.

这篇关于用Java将文件从一个目录复制到另一个目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆