Copying files from one directory to another in Java(在 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 中将文件从一个目录复制到另一个目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 中将文件从一个目录复制到另一个目录
基础教程推荐
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
