在 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.
相关文章