Java - Paths Ends Starts

Introduction

You can use the endsWith() and startsWith() methods to test if a path ends with and starts with a given path, respectively.

endsWith() and startsWith() test if a path ends and starts with components of another path, respectively.

The following code shows some examples of using these methods with paths on Windows:

Demo

import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
  public static void main(String[] args) {
    Path p1 = Paths.get("C:\\myData\\Main.java");
    Path p2 = Paths.get("Main.java");
    Path p3 = Paths.get("myData\\Main.java");
    Path p4 = Paths.get(".txt");

    // Using endsWith()
    boolean b1 = p1.endsWith(p2); 
    System.out.println(b1);//from  w  ww  . j  av  a2 s  .c o m
    boolean b2 = p1.endsWith(p3); 
    System.out.println(b2);
    boolean b3 = p1.endsWith(p4); 
    System.out.println(b3);

    // Using startsWith()
    Path p5 = Paths.get("C:\\");
    Path p6 = Paths.get("C:\\myData");
    Path p7 = Paths.get("C:\\poem");

    boolean b4 = p1.startsWith(p5); 
    System.out.println(b4);
    boolean b5 = p1.startsWith(p6); 
    System.out.println(b5);
    boolean b6 = p1.startsWith(p7); 
    System.out.println(b6);
  }
}

Result

Related Topic