How to move directories using jdk7

Using jdk7 , I am trying to use the java.nio.file.Files class to move an empty directory, say Bar , to another empty directory, say Foo

 Path source = Paths.get("Bar"); Path target = Paths.get("Foo"); try { Files.move( source, target, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } 

After executing this piece of code, I expected the Bar directory to be in the Foo directory ( ...\Foo\Bar ). Instead it is not. And here is the kicker, he was also removed. In addition, no exceptions were selected .

Am I doing it wrong?

Note

I am looking for a jdk7 solution. I am also studying the problem, but I decided that I would see if there was anyone else playing with jdk7.

EDIT

In addition to the accepted answer, here is another solution

 Path source = Paths.get("Bar"); Path target = Paths.get("Foo"); try { Files.move( source, target.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } 
+4
source share
3 answers

I did not understand jdk7 java.nio.file.Files - a necessity, so here is the edited solution. See if it works coz. I have never used the new Files class before.

 Path source = Paths.get("Bar"); Path target = Paths.get("Foo", "Bar"); try { Files.move( source, target, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } 
+4
source

In javadoc for the Files.move method, you will find an example in which it moves the file to a directory, keeping the same file name. This seems to be what you were looking for.

0
source

Here is the solution.


http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
Suppose we want to move the file to a new directory, keeping the same file name, and replace the existing file with the same name in the directory:
 Path source = ... Path newdir = ... Files.move(source, newdir.resolve(source.getFileName()), REPLACE_EXISTING); //Files.move(source, newdir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING); 
0
source

All Articles