How to create Path – Java NIO

As we know, that Path class, introduced in the Java SE 7 release, is one of the primary entry points of the java.nio.file package. If your application uses NIO, you should learn more about the powerful features available in this class. I am beginning the NIO tutorials with defining Path in NIO 2.

In this tutorial, I am listing 6 ways to create Path in NIO.

Note: I am building path for a file in location – “C:/Lokesh/Setup/workspace/NIOExamples/src/sample.txt”. I have created this file beforehand and will create Path to this file in given below examples.

Define absolute path

An absolute path always contains the root element and the complete directory list required to locate the file. There is no more information required further to access the file or path. We will use getPath() method with following signature.

/** * Converts a path string, or a sequence of strings that when joined form a path string, * to a Path. If more does not specify any elements then the value of the first parameter * is the path string to convert. If more specifies one or more elements then each non-empty * string, including first, is considered to be a sequence of name elements and is * joined to form a path string. */ public static Path get(String first, String… more);

Feedback, Discussion and Comments

thanks for the nice samples. However, I am looking desperately for a solution: I have a desktop Swing app, developed under NetBeans 7.3. I have some embedded data sources in my project. Something like myProject=>Source Packages=>data=>datfile1, datafile2 etc. How can I address this “embedded” path? Normally, I write simply “/data” – many interface understand it. Any help pls.? Thanks / Gabor

@max3d: No! You should not! freaking terrible advice – always use relative paths – especially if you have an app that is deployed on multiple architectures – Mac/ Linux/ BSD

Like why would you even use Java which provides all these lovely mechanism to get around OS compatibility issues and then do something stupid like hard coding paths in your application? newb level sauce right there.