views:

4678

answers:

9

Hello,

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

}
+1  A: 

you use renameTo() – not obvious, I know ... but it's the Java equivalent of move ...

phatmanace
But wouldn't that actually move the file instead of copying it?
Joey
I have written review.renameTo(trDir); in the for loop. however, it didn't work :(. The directory trDir was created, but empty. I have used it in the right way, haven't I?
Nothing happens with the files - they are neither moved, nor copied.
Actually, in my case, moving the file will be even better than copying it.
renameTo() requires as parameter a File object representing the *file itself* in its new directory - not that directory.
Michael Borgwardt
+6  A: 

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
Michael Borgwardt
+1 for NIO2: I'm experimenting with NIO2/Java7 these days.. and the new Path is very well engineered
dfa
A: 

The NIO classes make this pretty simple.

http://www.javalobby.org/java/forums/t17036.html

Nate
+1  A: 

If you want to copy a file and not move it you can code like this.

private static void copyFile(File sourceFile, File destFile)
  throws IOException {
 if (!sourceFile.exists()) {
  return;
 }
 if (!destFile.exists()) {
  destFile.createNewFile();
 }
 FileChannel source = null;
 FileChannel destination = null;
 source = new FileInputStream(sourceFile).getChannel();
 destination = new FileOutputStream(destFile).getChannel();
 if (destination != null && source != null) {
  destination.transferFrom(source, 0, source.size());
 }
 if (source != null) {
  source.close();
 }
 if (destination != null) {
  destination.close();
 }

}
Janusz
Hi, I have tried this, but I obtain error messages:java.io.FileNotFoundException: ...path to trDir... (Is a directory)Everything in my file and folders seem to be ok. Do you know what it going wrong, and why I get this?
But isn't there a Windows bug around the transferFrom not able to copy streams larger than 64MB in one piece? http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4938442 fix http://www.rgagnon.com/javadetails/java-0064.html
kd304
I am using Ubuntu 8.10, so this shouldn't be the problem.
If you are sure your code won't ever run on different platform.
kd304
@gemm the destfile has to be the exact path were the file should be copied to. This means including the new filename not only the directory you want to copy the file to.
Janusz
A: 

The example below from Java Tips is rather straight forward. I have since switched to Groovy for operations dealing with the file system - much easier and elegant. But here is the Java Tips one I used in the past. It lacks the robust exception handling that is required to make it fool-proof.

 public void copyDirectory(File sourceLocation , File targetLocation)
    throws IOException {

        if (sourceLocation.isDirectory()) {
            if (!targetLocation.exists()) {
                targetLocation.mkdir();
            }

            String[] children = sourceLocation.list();
            for (int i=0; i<children.length; i++) {
                copyDirectory(new File(sourceLocation, children[i]),
                        new File(targetLocation, children[i]));
            }
        } else {

            InputStream in = new FileInputStream(sourceLocation);
            OutputStream out = new FileOutputStream(targetLocation);

            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        }
    }
Brian
Thank you, but I don't want to copy the directory - only the files in it. Now I get error messages java.io.FileNotFoundException:(the path to trDir) (Is a directory)This is what it only says. I have used the method like this:copyDirectory(review, trDir);
+3  A: 

For now this should solve your problem

File source = new File("H:\\work-temp\\file");
File desc = new File("H:\\work-temp\\file2");
try {
    FileUtils.copyDirectory(source, desc);
} catch (IOException e) {
    e.printStackTrace();
}

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.

Arun P Johny
Where can I find the FileUtils class? In what library? It seems not to be from the standard ones in Java. Thanks.
Apache Commons io 'http://commons.apache.org/io/'
Robert
A: 

You seem to be looking for the simple solution (a good thing), to which I would recommend using Apache Common's FileUtil.copyDirectory

Copies a whole directory to a new location preserving the file dates.

This method copies the specified directory and all its child directories and files to the specified destination. The destination is the new location and name of the directory.

The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.

Your code could like nice and simple like this:

File trgDir = new File("/tmp/myTarget/");
File srcDir = new File("/tmp/mySource/");

FileUtils.copyDirectory(srcDir, trgDir);
Stu Thompson
Hi, I don't want to copy the directory - only the files in it.
It's basically the same thing, no? All the files from the source directory will end up in the the target directory.
Stu Thompson
A: 

Use org.apache.commons.io.FileUtils. It's so handy

Bhimesh