Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.nio.file: Where is the Path interface actually implemented?

Recently I was doing some coding using the java.nio.file package introduced in Java 7 and saw an example using Path like this:

Path path = Paths.get("C:\\Users");

Given that Path is an interface I was confused on how you could have a reference to it, however after some research I found out that a reference to an interface is allowed but it must point to a class that implements the interface. Looking on from this I looked at the Paths class and saw that it didn't implement Path. Looking at the source code the actual method Paths.get method is as follows:

public static Path get(String first, String... more) {
    return FileSystems.getDefault().getPath(first, more);
}    

the method first returns an object of type FileSystem (from an abstract class I think) using what I believe is called a static factory method, but FileSystem also doesn't implement the interface.

My question is does anyone know/able to explain where the Path interface is actually implemented as I cannot seem to find where this occurs.

like image 916
Levenal Avatar asked Dec 30 '13 08:12

Levenal


People also ask

What is Java NIO file paths?

Technically in terms of Java, Path is an interface which is introduced in Java NIO file package during Java version 7,and is the representation of location in particular file system.As path interface is in Java NIO package so it get its qualified name as java. nio. file.

How do file paths work in Java?

A path can point to either a file or a directory. A path can be absolute or relative. An absolute path contains the full path from the root of the file system down to the file or directory it points to. A relative path contains the path to the file or directory relative to some other path.

Which methods listed below are found in the NIO 2 path interface?

The NIO. 2 Path interface contains the methods getRoot() and toRealPath().

How do you give a directory path in Java?

The path for a file can be obtained using the method java. io. File. getPath().


1 Answers

If you look carefully you will notice that the method getPath from FileSystem object returns implementation of Path interface. By invoking FileSystems.getDefault() you will retrieve implementation of FileSystem interface which will depend on system. On Linux system you will get LinuxFileSystem object witch extends UnixFileSystem class.

You can look for example at UnixFileSystem class from openjdk which is implementation of FileSystem interface.

Here is the link with implementation of getPath method from UnixFileSystem, which will return instance of UnixPath.

You must remember that FileSystems.getDefault return implementation dependent on the operating system. Furthermore source code of those classes isn't available in oracle jdk.

like image 141
Marcin Wagner Avatar answered Oct 06 '22 01:10

Marcin Wagner