使用Java将文件从一个目录复制到另一个目录 [英] Copying files from one directory to another in Java
问题描述
我想使用Java将文件从一个目录复制到另一个目录(子目录)。我有一个目录,dir,有文本文件。我遍历dir中的前20个文件,并希望将它们复制到dir目录中的另一个目录,这是我在迭代之前创建的。
在代码中,我想将 review
(代表第i个文本文件或评论)复制到 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屋!