- Java NIO Path (with Examples)
- Example 1: Create an absolute Path to a file in Java NIO
- Example 2: Create relative Path to a given file
- Example 3: Create relative Path to current working directory
- Example 4: Get the absolute path of a file using file URI in Java NIO
- Example 5: Get absolute path of a file using system defaults
- Example 6: Get path of a file in the system download folder
- Java File Path, Absolute Path and Canonical Path
- Java File Path
- Java File Path Example
- Still looking for an answer?
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.
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");
Java File Path, Absolute Path and Canonical Path
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Java File Path
- getPath() : This file path method returns the abstract pathname as String. If String pathname is used to create File object, it simply returns the pathname argument. If URI is used as argument then it removes the protocol and returns the file name.
- getAbsolutePath() : This file path method returns the absolute path of the file. If File is created with absolute pathname, it simply returns the pathname. If the file object is created using a relative path, the absolute pathname is resolved in a system-dependent way. On UNIX systems, a relative pathname is made absolute by resolving it against the current user directory. On Microsoft Windows systems, a relative pathname is made absolute by resolving it against the current directory of the drive named by the pathname, if any; if not, it is resolved against the current user directory.
- [getCanonicalPath](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#getCanonicalPath())() : This path method returns the canonical pathname that is both absolute and unique. This method first converts this pathname to absolute form if necessary, as if by invoking the getAbsolutePath method, and then maps it to its unique form in a system-dependent way. This typically involves removing redundant names such as “.” and “…” from the pathname, resolving symbolic links (on UNIX platforms), and converting drive letters to a standard case (on Microsoft Windows platforms).
Java File Path Example
Let’s see different cases of the file path in java with a simple program.
package com.journaldev.files; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; public class JavaFilePath < public static void main(String[] args) throws IOException, URISyntaxException < File file = new File("/Users/pankaj/test.txt"); printPaths(file); // relative path file = new File("test.xsd"); printPaths(file); // complex relative paths file = new File("/Users/pankaj/../pankaj/test.txt"); printPaths(file); // URI paths file = new File(new URI("file:///Users/pankaj/test.txt")); printPaths(file); >private static void printPaths(File file) throws IOException < System.out.println("Absolute Path: " + file.getAbsolutePath()); System.out.println("Canonical Path: " + file.getCanonicalPath()); System.out.println("Path: " + file.getPath()); >>
Below image shows the output produced by the above java file path program. The output is self-explanatory. Based on the output, using the canonical path is best suitable to avoid any issues because of relative paths. Also, note that the java file path methods don’t check if the file exists or not. They just work on the pathname of the file used while creating the File object. That’s all for different types of the file path in java.
You can checkout more java IO examples from our GitHub Repository.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Still looking for an answer?
Hi Sir, I am trying to get the full path of the selected file. Below is the code. Please advise. I need to pass the full path and file name for the selected files to apache pdf box class to get the excel extracts. /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pdfet.pdfext; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.event.ActionListener; //import com.pdfet.pdfext.ExtensionFileFilter; import java.io.File; import javax.swing.filechooser.FileFilter; /** * * @author vak_salem */ class ExtensionFileFilter extends FileFilter < String descrip; String extn[]; public ExtensionFileFilter(String descrip,String Extn) < this(descrip,new String[] ); > public ExtensionFileFilter(String descrip, String extn[]) < if (descrip==null) < this.descrip=extn[0] + “”; > else < this.descrip=descrip; >this.extn=(String []) extn.clone(); toLower(this.extn); > private void toLower(String array[]) < for (int i=0,n=array.length;i