Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 722
ripper234 Avatar asked Nov 22 '11 13:11

ripper234


People also ask

What is Java NIO file paths?

Advertisements. As name suggests Path is the particular location of an entity such as file or a directory in a file system so that one can search and access it at that particular location.

How do I find the path of a file in Java?

In Java, for NIO Path, we can use path. toAbsolutePath() to get the file path; For legacy IO File, we can use file. getAbsolutePath() to get the file path.

What is import Java NIO file files?

Advertisements. Java NIO package provide one more utility API named as Files which is basically used for manipulating files and directories using its static methods which mostly works on Path object.


1 Answers

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");
like image 138
Erick Robertson Avatar answered Oct 17 '22 04:10

Erick Robertson