Java NIO and NIO2 Path Tutorial

Java NIO and NIO2 Path Tutorial

When Java 7 was released on July 28, 2011 Oracle introduced the NIO.2 framework which continued to add new features to the New I/O library they added the Paths Class and Path Interface. The Path interface defines various methods that may be used to get information about a path, transform a path from one form to another and extract parts of a path.

Topics Covered in this Tutorial

  1. Directory Structure
  2. Creating a Path
  3. Defining an Absolute Path in NIO2
  4. Absolute Path Output
  5. Defining a Relative Path in NIO2
  6. Relative Path Output
  7. Converting a Path to Real Path
  8. Complete Code (NIOPathExample.java)

Directory Structure

nio_paths

Creating a Path

Creating a Path object is easily done using the get() method from the Paths class.

Path myPath = Paths.get("/var/tmp/output.txt");
Path myURI = Paths.get(URI.create("file:///C:/tmp/output.txt"));

Defining an Absolute Path in NIO2

logger("*** Absolute Path ***");
Path absolutePath = Paths.get("C:", "WS", "JavaNIOExample",
  "src", "com", "avaldes", "tutorial", "NIOPathExample.java");
showAbsolutePath("Absolute Path", absolutePath);

Path absolutePath1 = Paths.get("src/com/avaldes", "tutorial",
  "NIOPathExample.java");
showAbsolutePath("Absolute Path1", absolutePath1);

Path absolutePath2 = Paths.get("C:/WS/JavaNIOExample/src",
  "/com/avaldes", "tutorial", "NIOPathExample.java");
showAbsolutePath("Absolute Path2", absolutePath2);
System.out.println();

Absolute Path Output (Text wrapped for blog purposes only)

Absolute Path............:
C:\WS\JavaNIOExample\src\com\avaldes\tutorial\NIOPathExample.java
Absolute Path1...........:
C:\WS\JavaNIOExample\src\com\avaldes\tutorial\NIOPathExample.java
Absolute Path2...........:
C:\WS\JavaNIOExample\src\com\avaldes\tutorial\NIOPathExample.java

Defining a Relative Path in NIO2

A relative path may be defined as a partial path that starts at a place other than the root folder/directory. They generally begin at some working folder or directory and specify the location of a directory relative to another. Creating a Relative Path object is easily done using the same get() method from the Paths class as used in previous examples.

Current Directory and Parent Directory

. (one ellipse) current directory
.. (two ellipses) parent directory (one level up the hierarchy)

In the directory structure image shown below, if our starting point was the var (#1) directory and we wanted to get to the scripts (#2) folder then the relative path would be “../users/amaury/scripts”. The .. (two ellipses) means “go the the parent directory”, in other words, “go up the tree” from the current directory of “var”, then go down to the directory called “users”, then go down into “amaury” and finally go into a directory called “scripts”.

nio_paths2

Using Relative Path Method in NIO2

logger("*** Relative Path ***");
Path relativePath = Paths.get("src/com/avaldes", "tutorial",
    "NIOPathExample.java");
Path absolutePath3 = relativePath.toAbsolutePath();
formatLogger("Relative Path", 25, relativePath.toString());
formatLogger("Absolute Path", 25, absolutePath3.toString());
testRealPath(absolutePath3);
System.out.println();

Relative Path Output (Text wrapped for blog purposes only)

*** Relative Path ***
Relative Path............:
src\com\avaldes\tutorial\NIOPathExample.java
Absolute Path............:
C:\WS\JavaNIOExample\src\com\avaldes\tutorial\NIOPathExample.java
Real Path................:
C:\WS\JavaNIOExample\src\com\avaldes\tutorial\NIOPathExample.java

Converting a Path to Real Path

Java NIO.2 provides a method toRealPath(LinkOption… options) to convert paths to real paths to an existing file in the operating system. This method throWS an exception if the file does not exist or is unable to be accessed. The toRealPath(LinkOption… options) method alloWS you to pass in LinkOption Enums in a variable list of arguments. If no argument is passed to the toRealPath() method then symbolic links are resolved provided the underlying operating system supports it. If you wish to ignore symbolic links, then you should pass the constant LinkOption.NOFOLLOW_LINKS.

Path p = Paths.get("C:", "WS", "JavaNIOExample",
   "src", "com", "avaldes", "tutorial", "NIOPathExample.java");
try {
  Path real_path = p.toRealPath();
  formatLogger("Real Path", 25, real_path.toString());
} catch (NoSuchFileException ex) {
  System.out.println("No Such File Exists!!!");
} catch (IOException ex) {
  System.out.println("I/O Exception, unable to find !!!");
}

Complete Code (NIOPathExample.java)

package com.avaldes.tutorial;

import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.commons.lang3.StringUtils;

public class NIOPathExample {

 public static void main(String[] args) {
  logger("Starting NIOPathExample");

  Path path = Paths.get("NIOPathExample.java");
  showDetails("Relative Path", path);
  System.out.println();

  logger("*** Absolute Path ***");
  Path absolutePath = Paths.get("C:", "WS", "JavaNIOExample",
    "src", "com", "avaldes", "tutorial", "NIOPathExample.java");
  showAbsolutePath("Absolute Path", absolutePath);
  testRealPath(absolutePath);

  Path absolutePath1 = Paths.get("src/com/avaldes", "tutorial",
    "NIOPathExample.java");
  showAbsolutePath("Absolute Path1", absolutePath1);
  testRealPath(absolutePath1);


  Path absolutePath2 = Paths.get("C:/WS/JavaNIOExample/src",
    "/com/avaldes", "tutorial", "NIOPathExample.java");
  showAbsolutePath("Absolute Path2", absolutePath2);
  testRealPath(absolutePath2);
  System.out.println();

  logger("*** Normalize Path ***");
  Path normalizePath = Paths.get("C:/WS/JavaNIOExample/test/test1
  /../../src/com/./avaldes/tutorial/NIOPathExample.java");
  formatLogger("Path w/o Normalize()", 25, normalizePath.toString());
  formatLogger("Path with Normalize()", 25, normalizePath
                                              .normalize().toString());
  testRealPath(normalizePath);
  System.out.println();

  logger("*** URI Path ***");
  Path uriPath = Paths.get(URI.create("file:///C:/WS
  /JavaNIOExample/src/com/avaldes/tutorial/NIOPathExample.java"));
  formatLogger("Path From URI", 25, uriPath.toString());
  testRealPath(uriPath);
  System.out.println();

  logger("*** FileSystem ***");
  FileSystem fs = FileSystems.getDefault();
  Path fsPath = fs.getPath("com/avaldes/tutorial", "NIOPathExample.java");
  formatLogger("FileSystem Path", 25, fsPath.toString());
  testRealPath(fsPath);
 }

 public static void showAbsolutePath(String title, Path p) {
  formatLogger(title, 25, p.toAbsolutePath().toString());
 }

 public static void testRealPath(Path p) {
  try {
   formatLogger("Real Path", 25, p.toRealPath().toString());
  } catch (NoSuchFileException ex) {
   System.out.println("No Such File Exists!!!");
  } catch (IOException ex) {
   System.out.println("I/O Exception, unable to find !!!");
  }
 }

 public static void showDetails(String title, Path p) {
  logger("=============================================");
  logger(String.format("*** %s ***", title));
  formatLogger("Path Name", 25, p.getFileName().toString());
  formatLogger("Path toAbsolutePath()", 25, p.toAbsolutePath().toString());
  formatLogger("Path File System", 25, p.getFileSystem().toString());
  formatLogger("Path Name Count", 25, String.valueOf(p.getNameCount()));
  formatLogger("Path toURI()", 25, p.toUri().toString());
  formatLogger("Path toAbsolutePath()", 25, p.toAbsolutePath().toString());
 }

 public static void logger(String msg) {
  System.out.println(msg);
 }

 public static void formatLogger(String title, int pad, String msg) {
  System.out.println(StringUtils.rightPad(title, pad, ".") + ": " + msg);
 }
}

Complete Code Output (Text wrapped for blog purposes only)

Starting NIOPathExample
=============================================
*** Relative Path ***
Path Name.............: NIOPathExample.java
Path toAbsolutePath().: C:\WS\JavaNIOExample\NIOPathExample.java
Path File System......: sun.nio.fs.WindoWSFileSystem@6bc7c054
Path Name Count.......: 1
Path toURI()..........:
file:///C:/WS/JavaNIOExample/NIOPathExample.java
Path toAbsolutePath().: C:\WS\JavaNIOExample\NIOPathExample.java

*** Absolute Path ***
Absolute Path............:
C:\WS\JavaNIOExample\src\com\avaldes\tutorial\NIOPathExample.java
Real Path................:
C:\WS\JavaNIOExample\src\com\avaldes\tutorial\NIOPathExample.java
Absolute Path1...........:
C:\WS\JavaNIOExample\src\com\avaldes\tutorial\NIOPathExample.java
Real Path................:
C:\WS\JavaNIOExample\src\com\avaldes\tutorial\NIOPathExample.java
Absolute Path2...........:
C:\WS\JavaNIOExample\src\com\avaldes\tutorial\NIOPathExample.java
Real Path................:
C:\WS\JavaNIOExample\src\com\avaldes\tutorial\NIOPathExample.java

*** Normalize Path ***
Path w/o Normalize().....: C:\WS\JavaNIOExample\test\test1\
..\..\src\com\.\avaldes\tutorial\NIOPathExample.java
Path with Normalize()....:
C:\WS\JavaNIOExample\src\com\avaldes\tutorial\NIOPathExample.java
Real Path................:
C:\WS\JavaNIOExample\src\com\avaldes\tutorial\NIOPathExample.java

*** URI Path ***
Path From URI............:
C:\WS\JavaNIOExample\src\com\avaldes\tutorial\NIOPathExample.java
Real Path................:
C:\WS\JavaNIOExample\src\com\avaldes\tutorial\NIOPathExample.java

*** FileSystem ***
FileSystem Path..........:
com\avaldes\tutorial\NIOPathExample.java
No Such File Exists!!!

Java NIO Related Tutorials

  • Java NIO Tutorial
    In this tutorial series we discuss the new features of Java NIO.
  • Java NIO Buffers
    This post covers NIO Buffers in more detail and provides practical examples of using buffers in real world applications.
  • Java NIO Channels
    This post covers NIO Channels in more detail and provides examples on network connections and Java I/O in relation to files.
  • Java NIO Selectors
    In this tutorial we learn how to use the Selector class from the java.io.channels package library to build High-Performance I/O client-server using NIO.
  • Java NIO File Channel
    In this tutorial we learn how to use the FileChannel class from the java.io.channels package library and provide working examples on all of the main methods.
  • Java NIO Socket Channel
    In this tutorial we learn how to use the SocketChannel and how it is used for reading/writing stream oriented data and using TCP connection based protocol.
  • Java NIO DatagramChannel Tutorial
    In this tutorial we learn how to use the DatagramChannel to allow developers to build high-performant data streaming applications that send and receive datagrams using a protocol called UDP.
  • Java NIO and NIO2 Path Tutorial
    This tutorial will introduce the Path interface and many of its methods. The Path interface was made available as part of the Java SE 7 release in the Java NIO 2 File API.

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *