java パスから開始位置と終了位置を指定してパスの値を取得する

java パスから開始位置と終了位置を指定してパスの値を取得する

javaで、パスから開始位置と終了位置を指定してパスの値を取得する手順を記述してます。

環境

  • OS windows11 home
  • java 17.0.2

手順

パスから開始位置と終了位置を指定してパスの値を取得するには、「subpath」を使用します。

パス.subpath(開始位置0から,終了位置より1つプラス);  

実際に、使用してみます。

import java.nio.file.Path;

public class App {
    public static void main(String[] args) throws Exception {
          
        // パスに変換
        Path path = Path.of("C:/hoge0/foo1/java2/sample3.txt");    
        
        System.out.println(path.subpath(0,2)); // hoge0\foo1
        System.out.println(path.subpath(1,3)); // foo1\java2     

    }
}

取得されていることが確認できます。

範囲を超える

範囲を超える場合は「IllegalArgumentException」が発生します。

import java.nio.file.Path;

public class App {
    public static void main(String[] args) throws Exception {
          
        // パスに変換
        Path path = Path.of("C:/hoge0/foo1/java2/sample3.txt");         
        
        System.out.println(path.subpath(1,5));
        // Exception in thread "main" java.lang.IllegalArgumentException    

    }
}