Question

Can anyone tell me what I've done wrong with the following code. I receive no errors - it just goes straight to the catch.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

    public static void main(String[] args) {
         Path source = Paths.get("C:\\Users\\Public\\Pictures\\SamplePictures");
    Path nwdir = Paths.get("D:\\NetbeansProjects\\CopyingFiles\\copiedImages");

    try{
    Files.copy(source, nwdir);
    }catch (IOException e){
        System.out.println("Unsucessful. What a surprise!");
    }
    }
}
Was it helpful?

Solution

If you take a look at the Javadocs of Files.copy, you'll notice this line (emphasis added):

If the file is a directory then it creates an empty directory in the target location (entries in the directory are not copied). This method can be used with the walkFileTree method to copy a directory and all entries in the directory, or an entire file-tree where required.

So it looks like you need to use that walkFileTree method.

(And as the commenters said, print out exceptions and they'll often tell you what's wrong!)

OTHER TIPS

Came across here looking for a NIO Java7 approach to recursively copy a directory to another location. This can be done with Files.walkFileTree as Jon7 mentioned in the other anwer. This code I got for a simple directory copy:

final Path srcDir, final Path dstDir;
Files.walkFileTree(srcDir, new SimpleFileVisitor<Path>() {
    public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) throws IOException {
        return copy(file);
    }
    public FileVisitResult preVisitDirectory( Path dir, BasicFileAttributes attrs ) throws IOException {
        return copy(dir);
    }
    private FileVisitResult copy( Path fileOrDir ) throws IOException {
        Files.copy( fileOrDir, dstDir.resolve( srcDir.relativize( fileOrDir ) ) );
        return FileVisitResult.CONTINUE;
    }
});

For a more detailed example which also handles file attributes and overwriting of existing files, see http://docs.oracle.com/javase/tutorial/essential/io/examples/Copy.java .

This is how I have managed to copy a file from one location to another:

import java.io.IOException;
import static java.nio.file.StandardCopyOption.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class App  {

 public static void main(String[] args)
 {
    Path source = Paths.get("E:/myFile.pdf");
    Path nwdir = Paths.get("F:");
    try
    { 
       Files.copy(source, nwdir.resolve(source.getFileName()), REPLACE_EXISTING);
       System.out.println("File Copied");
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
 }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top