How to access a sub-file/folder in Java 7 java.nio.file.Path?

China☆狼群 提交于 2019-12-17 22:54:51

问题


Java 7 introduced java.nio.file.Path as a possible replacement for java.io.File.

With File, when I access a file under a specific, I would do:

File parent = new File("c:\\tmp");
File child = new File(parent, "child"); // this accesses c:\tmp\child

What's the way to do this with Path?

I supposed this will work:

Path parent = Paths.get("c:\\tmp");
Path child = Paths.get(parent.toString(), "child");

But calling parent.toString() seems ugly. Is there a better way?


回答1:


Use the resolve method on Path.

There are two methods with this name. One takes a relative Path and the other a String. It uses the Path on which it is called as a parent and appends the String or relative Path appropriately.

Path parent = Paths.get("c:\\tmp");
Path child = parent.resolve("child");


来源:https://stackoverflow.com/questions/8227499/how-to-access-a-sub-file-folder-in-java-7-java-nio-file-path

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