Site Search:

Use Path interface to operate on file and directory paths

Back>

OCPJP requires familiar with some methods of
java.nio
java.nio

  1. public interface Path extends Comparable<Path>, Iterable<Path>, Watchable
  2. public final class Paths
  3. public final class Files
  4. public abstract class FileSystem implements Closeable
  5. public final class FileSystems
Paths is a factory class to create Path object. Paths.get() is equivalent to FileSystem.getDefault().getPath()
  • Paths.get(String first, String...more)
  • Paths.get(URI uri) 
Uniform resource identifier (URI) is a string of characters the identify a resource. It begins with a schema indicating resource type, (for example: file://, https://, http://, ftp://) followed by a path (for example /, /home/, www.google.com, username:userpasswd@gmail.com).

So new URI("file:///"); is valid, new URI("file://home/file.txt"); throws exception. 

OCPJP>cat PathDemo.java
import java.io.IOException;
import java.nio.file.*;

public class PathDemo {
    public static void main(String[] args) {
        Path path = Paths.get("/home/fakeDir/..", "FakeFile.jpg");
        test(path);
        path = Paths.get("home", "fakeDir/..", "FakeFile.jpg");
        test(path);
        
        Path from = Paths.get("from.txt");
        Path to = Paths.get("to.txt");
        tests(from, to);
        
        from = Paths.get("/somewhere/from.txt");
        to = Paths.get("/somewhere/to.txt");
        tests(from, to);
        
        from = Paths.get("/somewhere/from.txt");
        to = Paths.get("/somewhereelse/to.txt");
        tests(from, to);
        
        from = Paths.get("from.txt");
        to = Paths.get("/somewhereelse/to.txt");  
        tests(from, to);  //throws
        
        try {
            path.toRealPath();  //throws
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
    
    private static void tests(Path from, Path to) {
        System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        try {
            Path path = from.resolve(to);
            System.out.println(path);
            path = from.relativize(to);
            System.out.println(path);
        } catch(Exception e) {
            e.printStackTrace();
        }
        
        
    }
    
    private static void test(Path path) {
        System.out.println("=====================================");
        System.out.println(path.toString());
        System.out.println(path.normalize());
        
        System.out.println(path.getNameCount());
        System.out.println(path.getFileName());
        System.out.println(path.getRoot());
        System.out.println(path.getParent());
        System.out.println(path.normalize().getParent());
        System.out.println(path.getParent().normalize());
        System.out.println(path.getName(0));
        System.out.println(path.getName(1));
        System.out.println(path.getName(2));
        System.out.println(path.getName(3));
        
        //System.out.println(path.normalize().getName(3)); //java.lang.IllegalArgumentException
        
        System.out.println(path.isAbsolute());
        System.out.println(path.toAbsolutePath());
        System.out.println(path.subpath(0, 2));
        System.out.println(path.subpath(1, 2));
    }

}
OCPJP>javac PathDemo.java 
OCPJP>java PathDemo
=====================================
/home/fakeDir/../FakeFile.jpg
/home/FakeFile.jpg
4
FakeFile.jpg
/
/home/fakeDir/..
/home
/home
home
fakeDir
..
FakeFile.jpg
true
/home/fakeDir/../FakeFile.jpg
home/fakeDir
fakeDir
=====================================
home/fakeDir/../FakeFile.jpg
home/FakeFile.jpg
4
FakeFile.jpg
null
home/fakeDir/..
home
home
home
fakeDir
..
FakeFile.jpg
false
/Users/homenetwork/OCPJP/home/fakeDir/../FakeFile.jpg
home/fakeDir
fakeDir
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
from.txt/to.txt
../to.txt
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
/somewhere/to.txt
../to.txt
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
/somewhereelse/to.txt
../../somewhereelse/to.txt
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
/somewhereelse/to.txt
java.lang.IllegalArgumentException: 'other' is different type of Path
at sun.nio.fs.UnixPath.relativize(UnixPath.java:416)
at sun.nio.fs.UnixPath.relativize(UnixPath.java:43)
at PathDemo.tests(PathDemo.java:40)
at PathDemo.main(PathDemo.java:25)
java.nio.file.NoSuchFileException: home/fakeDir/../FakeFile.jpg
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixPath.toRealPath(UnixPath.java:837)
at PathDemo.main(PathDemo.java:28)
OCPJP>

Notice Paths.get() don't throw exception if a file or directory doesn't actually exist; and new URI(String uri) throws checked exception URISyntaxException.

File interface has many methods we need to know for the OCPJP exam. The following code is an example of their usage.

OCPJP>cat PathsDemo.java 
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathsDemo {
    public static void main(String...args) {
        Path path = Paths.get("/");
        System.out.println(path);
        path = FileSystems.getDefault().getPath("/");
        System.out.println(path);
        System.out.println(Paths.get("/","home", "nosuchFile.txt"));
        System.out.println(Paths.get("/", "nosuchDir"));
        System.out.println(Paths.get("relativeDir/maybeExistsFile.txt"));
        System.out.println(Paths.get("relativeDir", "myabeExistsFile.txt"));
        System.out.println(Paths.get("E:\\fakeWindowsDir\\fakeWindowsfile.txt"));
        System.out.println(Paths.get("E:", "fakeWindowsDir", "fakeWindowsfile.txt"));
        try {
            //Paths.get(new URI("http://www.google.com"));
            System.out.println(Paths.get(new URI("file:///maybeExistsDir/maybeExistsFile.txt")));
            System.out.println(Paths.get(new URI("file://etc")));
        } catch (URISyntaxException e) {
            System.out.println("not a URISyntaxException, a Runtime Exception instead.");
        }
    }

}
OCPJP>javac PathsDemo.java 
OCPJP>java PathsDemo
/
/
/home/nosuchFile.txt
/nosuchDir
relativeDir/maybeExistsFile.txt
relativeDir/myabeExistsFile.txt
E:\fakeWindowsDir\fakeWindowsfile.txt
E:/fakeWindowsDir/fakeWindowsfile.txt
/maybeExistsDir/maybeExistsFile.txt
Exception in thread "main" java.lang.IllegalArgumentException: URI has an authority component
at sun.nio.fs.UnixUriUtils.fromUri(UnixUriUtils.java:53)
at sun.nio.fs.UnixFileSystemProvider.getPath(UnixFileSystemProvider.java:98)
at java.nio.file.Paths.get(Paths.java:138)
at PathsDemo.main(PathsDemo.java:21)
OCPJP>


So far, we are handling file's path as a string using java.nio.file.Paths, we haven't interacted with the actual file or directory the Path instance representing. The java.nio.file.Files is the class doing that, which we will cover in the next topic.