HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java New Input/Output / Java NIO Path (with Examples)

Java NIO Path (with Examples)

The Path class, introduced in the Java SE 7 release, is one of the primary entry points of the java.nio.file package. If our application uses Java New IO, we should learn more about the powerful features available in this class.

In this Java tutorial, we are learning 6 ways to create a Path.

Table of Contents

1. Building the absolute path
2. Building path relative to file store root
3. Building path relative to the current working directory
4. Building path from URI scheme
5. Building path using file system defaults
6. Building path using System.getProperty()

Prerequisite: 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 all examples.

1. Building Absolute Path

An absolute path always contains the root element and the complete directory hierarchy required to locate the file. There is no more information required further to access the file or path.

To create an absolute path to a file, use getPath() method.

/**
* 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);

Example 1: Create an absolute Path to a file in Java NIO

In all given examples, we are creating the absolute path for the same file, in different ways.

//Starts with file store root or drive
Path absolutePath1 = Paths.get("C:/Lokesh/Setup/workspace/NIOExamples/src", "sample.txt");

Path absolutePath2 = Paths.get("C:/Lokesh/Setup/workspace", "NIOExamples/src", "sample.txt");

Path absolutePath3 = Paths.get("C:/Lokesh", "Setup/workspace", "NIOExamples/src", "sample.txt");

2. Building path relative to file store root

Path relative to file store root starts with a forward-slash (“/”) character.

Example 2: Create relative Path to a given file

//How to define path relative to file store root (in windows it is c:/)
Path relativePath1 = FileSystems
		.getDefault()
		.getPath("/Lokesh/Setup/workspace/NIOExamples/src", "sample.txt");

Path relativePath2 = FileSystems
		.getDefault()
		.getPath("/Lokesh", "Setup/workspace/NIOExamples/src", "sample.txt");

3. Building path relative to current working directory

To define the path relative to the current working directory, do not use either file system root (c:/ in windows) or slash (“/”).

Example 3: Create relative Path to current working directory

In given example, the current working directory is NIOExamples.

//How to define path relative to current working directory 
Path relativePath1 = Paths.get("src", "sample.txt");

4. Building path from URI scheme

Not frequently, but at times we might face a situation where we would like to convert a file path in format “file:///src/someFile.txt” to NIO path.

Example 4: Get the absolute path of a file using file URI in Java NIO

//Writing c:/ is optional
//URI uri = URI.create("file:///c:/Lokesh/Setup/workspace/NIOExamples/src/sample.txt");  

URI uri = URI.create("file:///Lokesh/Setup/workspace/NIOExamples/src/sample.txt");

String scheme =  uri.getScheme();
if (scheme == null)
	throw new IllegalArgumentException("Missing scheme");

//Check for default provider to avoid loading of installed providers
if (scheme.equalsIgnoreCase("file"))
{
	String absPath = FileSystems.getDefault()
					.provider()
					.getPath(uri)
					.toAbsolutePath()
					.toString();

	System.out.println(absPath);
}

//If you do not know scheme then use this code. 
//This code check file scheme as well if available.
for (FileSystemProvider provider: FileSystemProvider.installedProviders()) 
{
	if (provider.getScheme().equalsIgnoreCase(scheme)) 
	{
		String absPath = provider.getPath(uri)
					.toAbsolutePath()
					.toString();

		System.out.println(absPath);
	}
}

5. Building path using file system default

This is another variation of above examples where instead of using Paths.get(), we can use FileSystems.getDefault().getPath() method.

The rules for absolute and relatives paths are the same as the above methods.

Example 5: Get absolute path of a file using system defaults

FileSystem fs = FileSystems.getDefault();

//relative path
Path path1 = fs.getPath("src/sample.txt");	

//absolute path
Path path2 = fs.getPath("C:/Lokesh/Setup/workspace/NIOExamples/src", "sample.txt");

6. Building path using System.getProperty()

Well, this is off the course, but good to know. We can use system-specific System.getProperty() also to build Path for specific files.

Example 6: Get path of a file in the system download folder

Path path1 = FileSystems.getDefault()
			.getPath(System.getProperty("user.home"), "downloads", "somefile.txt");

Happy Learning !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Binh Thanh Nguyen

    February 26, 2014

    Thanks, nice post.

  2. Gabor Markon

    October 17, 2013

    Hi Lokesh,

    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

    • Lokesh Gupta

      October 17, 2013

      No idea around netbeans. Probably fellow learners can take this up. Anybody, would like to solve?

    • Max3d

      January 31, 2014

      You should use absolute path to the files in your project, like “D://Java programs//SomeProject//build//web//resources//img//

      • radaradarada

        January 21, 2015

        @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.

Comments are closed on this article!

Search Tutorials

Java New IO

  • Java NIO Introduction
  • Java NIO Path
  • Java NIO Buffers
  • Java NIO Channels
  • Java NIO Read File
  • Java NIO MappedByteBuffer
  • Java NIO Vectored IO
  • Data Transfer between Channels

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)