简体   繁体   English

如何使用jdk7移动目录

[英]How to move directories using jdk7

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使用jdk7 ,我正在尝试使用java.nio.file.Files class 一个空目录(比如说Bar )移动到另一个空目录中,比如说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 ).执行该代码片段后,我预计Bar目录将位于Foo目录( ...\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.我正在寻找特定于 jdk7 的解决方案。我也在研究这个问题,但我想我会看看是否还有其他人在玩 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();
}

I didn't realize jdk7 java.nio.file.Files is a necessity, so here is the edited solution.我没有意识到 jdk7 java.nio.file.Files 是必需品,所以这里是编辑的解决方案。 Please see if it works coz I have never used the new Files class before.请看看它是否有效,因为我以前从未使用过新的文件 class。

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

Here is the solution.这是解决方案。


http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html 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);

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.在 Files.move 方法的 javadoc 中,您将找到一个示例,它将文件移动到目录中,并保持相同的文件名。 This seems to be what you were looking for.这似乎是你要找的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM