Home  >  Java 7

Example of Path and Paths in java.nio.file API

By Arvind Rai, November 27, 2013
Path is an interface and Paths is a final class of java.nio.file API. Path has been introduced in JDK 7. The use of Path is to locate a file in file system. Path has flexibility to locate the file by proving path in parts. Path provides file path attribute like file name, file system, parent name and root. Paths are used to get Path instance by its static method. Path returns java.io.File when we call Path.toFile(). Now we will see how to create the instance of Path. The instance of Path can be obtained by FileSystems and Paths class.

Create Path Instance by Paths

If we have a file located in the path as c:\temp\test.txt. We can get this path in many ways.
Path path = Paths.get("c:/temp/test.txt" ); 
Path path = Paths.get("c:/temp","test.txt" );
Path path = Paths.get("c:","temp/test.txt" );
Path path = Paths.get("c:","temp","test.txt");
This is because Paths.get(String first, String more...) can accept one or more than one argument.


Create Path Instance by FileSystems

The Path instance can also be obtained using java.nio.file.FileSystems as below.
Path path = FileSystems.getDefault().getPath("c:","temp","test.txt");
Now find the example of Path and Paths.

PathExample.java
package com.concretepage.io.file;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathExample {
	public static void main(String[] args) throws IOException {
		//Get the instance of Path
		Path path = Paths.get("c:","temp","test.txt");
		//Print the path attributes
		System.out.println(path.getFileName());
		System.out.println(path.getFileSystem());
		System.out.println(path.getParent());
		System.out.println(path.getRoot());
		
	        //Gets File Object
		File f = path.toFile();
		System.out.println(f.getAbsoluteFile());
		
		//Read File wit the help of Path
	        BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
 	        String s = null;
	        while((s=reader.readLine())!=null){
	    	System.out.println(s);	
	        }
	}
}
 
PathExample.java gives the demo of how to use Path and Paths. What is going in it is that we have created Path instance with the help of Paths.get method. We are getting instance of java.io.File with the help of Path.toFile. Finally BufferedReader is printing data in console. Find the Output.

Output
test.txt
sun.nio.fs.WindowsFileSystem@4cf8f332
c:\temp
c:\
c:\temp\test.txt
Hellow World!
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us