So you've got a path string that you want to convert to a Path object? There's a method for that.

In fact, it's a static method. So it's easy to access.

And it's part of Java NIO.

In this guide, I'll show you how to use it.

Paths: The Plurality

The static method that I mentioned above is parth of the Paths class. It's imaginitively named get().

That get() method takes a String object that specifies the full path.

So if you want to get the full path to /etc/careydevelopment, you'd do it like so:

Path path = Paths.get("/etc/careydevelopment");

Well that ain't nothin' to write home about.

And, truth be told, you could stop reading right here. But there are other ways to get a Path object. 

With Path Segments

Although the solution above works just fine, some developers prefer to use path segments. Like this:

Path path = Paths.get("C:\\", "etc", "careydevelopment");

And that will work just fine as well.

You could also use just a single slash on the C: portion.

And, of course, if you're using a Unix operating system, you won't be needing the C: portion.

But enough with the disclaimers.

When you opt for a solution like the one above, you put each path segment as a separate parameter in the get() method. You can get away with that because get() is overloaded.

This solution is helpful if you want to pass in different path segments as variables but don't want to do any string concatenation.

To Of Or Not To Of

The of() static method seems to get a lot of mileage these days. You can use it with Path like this:

Path path = Path.of("C:/", "etc", "careydevelopment");

Or you can pass the whole path in:

Path path = Path.of("/etc/careydevelopment");

Once again: it works either way. Pass in path segments or the whole thing as a String object.

Just keep in mind: the of() method works with Path (singular) while the get() method works with Paths (plural).

Wrapping It Up

Painless. Perfectly painless.

Now you know how to create a Path object from a simple string using Java NIO.

Of course, you'll have to adapt what you've learned here to suit your own business requirements. But that won't be too difficult.

Have fun!