如何使用jdk7移动目录
使用jdk7,我尝试使用java.nio.file.Files
类移动一个空目录,比如说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();
}
执行该代码片段后,我期望Bar
目录将位于 Foo
目录 (...\Foo\Bar
) 中。相反,事实并非如此。更重要的是,它也被删除了。此外,没有抛出异常。
我这样做错了吗?
注意
我正在寻找特定于jdk7的解决方案。我也在研究这个问题,但我想我会看看是否有其他人在玩jdk7 。
编辑
除了接受的答案之外,这里还有另一个解决方案
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();
}
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我没有意识到 jdk7 java.nio.file.Files 是必需的,所以这里是编辑后的解决方案。请看看它是否有效,因为我以前从未使用过新的 Files 类。
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.
在 Files.move 方法的 javadoc 中,您将找到一个示例,它将文件移动到目录中,并保持相同的文件名。这似乎就是您正在寻找的。
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.
这是解决方案。
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:
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: