Copying files from one directory to another in Java
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];
}
Solution 1:
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
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.
Solution 2:
There is no file copy method in the Standard API (yet). Your options are:
- Write it yourself, using a FileInputStream, a FileOutputStream and a buffer to copy bytes from one to the other - or better yet, use FileChannel.transferTo()
- User Apache Commons' FileUtils
- Wait for NIO2 in Java 7