How to move directories using jdk7

牧云@^-^@ 提交于 2019-12-12 11:26:21

问题


Using jdk7, I am trying to use the java.nio.file.Files class to move an empty directory, let's say Bar, into another empty directory, let's 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 that code snippet, I expected that the Bar directory would be in the Foo directory (...\Foo\Bar). Instead it is not. And here's the kicker, it's been deleted as well. Also, no exceptions were thrown.

Am I doing this wrong?

NOTE

I'm looking for a jdk7-specific solution.I am also looking into the problem, but I figured I'd see if there was anyone else playing around with jdk7.

EDIT

In addition to the accepted answer, here's 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();
}

回答1:


I didn't realize jdk7 java.nio.file.Files is a necessity, so here is the edited solution. Please 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();
}



回答2:


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




回答3:


Here is the solution.


http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
suppose we want to move a file to new directory, keeping the same file name, and replacing any existing file of that 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);


来源:https://stackoverflow.com/questions/6210433/how-to-move-directories-using-jdk7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!