広告

Java : Path (パス) - API使用例

Path (Java SE 22 & JDK 22) の使い方まとめです。
ほとんどのメソッドにサンプルコードがあります。
API仕様書のおともにどうぞ。

注意

  • デフォルトの FileSystemProvider によって、結果や表示が異なることがあります。
  • 本記事では Windows 10 で実行した結果となります。

概要

ファイル・システム内のファイルを特定するために使用可能なオブジェクトです。 通常、それはシステムに依存するファイル・パスを表します。

クラス構成

Path インタフェースは、システム内のファイルやディレクトリ(フォルダ) を表します。

関連記事:ファイル操作の基本

final var path = Path.of("D:", "java-work", "sample.txt");
System.out.println(path); // "D:\java-work\sample.txt"

System.out.println(Files.exists(path)); // false

Files.writeString(path, """
        aaa
        bbb
        ccc
        """);

System.out.println(Files.exists(path)); // true

final var str = Files.readString(path);
System.out.println(str);

// 結果
// ↓
//aaa
//bbb
//ccc

メソッド

int compareTo (Path other)

2つの抽象パスを語彙的に比較します。

System.out.println(System.getProperty("os.name")); // Windows 10

// Windows は大文字小文字の区別はありません。
final var path1 = Path.of("aaa.txt");
final var path2 = Path.of("AAA.txt");

System.out.println(path1); // "aaa.txt"
System.out.println(path2); // "AAA.txt"
System.out.println(path1.compareTo(path2)); // 0
final var path1 = Path.of("aaa.txt");
final var path2 = Path.of("bbb.txt");

System.out.println(path1); // "aaa.txt"
System.out.println(path2); // "bbb.txt"
System.out.println(path1.compareTo(path2)); // -1
System.out.println(path2.compareTo(path1)); // 1
final var path1 = Path.of("12.txt");
final var path2 = Path.of("123.txt");

System.out.println(path1); // "12.txt"
System.out.println(path2); // "123.txt"
System.out.println(path1.compareTo(path2)); // -5
System.out.println(path2.compareTo(path1)); // 5
final var path1 = Path.of("99.jpg");
final var path2 = Path.of("123.jpg");

System.out.println(path1); // "99.jpg"
System.out.println(path2); // "123.jpg"
System.out.println(path1.compareTo(path2)); // 8
System.out.println(path2.compareTo(path1)); // -8
final var path1 = Path.of("dir1", "a.txt");
final var path2 = Path.of("dir1", "b.txt");
final var path3 = Path.of("dir2", "a.txt");
final var path4 = Path.of("dir2", "b.txt");

System.out.println(path1); // "dir1\a.txt"
System.out.println(path2); // "dir1\b.txt"
System.out.println(path3); // "dir2\a.txt"
System.out.println(path4); // "dir2\b.txt"

System.out.println(path1.compareTo(path2)); // -1
System.out.println(path1.compareTo(path3)); // -1
System.out.println(path1.compareTo(path4)); // -1

System.out.println(path2.compareTo(path1)); // 1
System.out.println(path2.compareTo(path3)); // -1
System.out.println(path2.compareTo(path4)); // -1

System.out.println(path3.compareTo(path1)); // 1
System.out.println(path3.compareTo(path2)); // 1
System.out.println(path3.compareTo(path4)); // -1

System.out.println(path4.compareTo(path1)); // 1
System.out.println(path4.compareTo(path2)); // 1
System.out.println(path4.compareTo(path3)); // 1
final var path1 = Path.of("dir");
final var path2 = Path.of("dir", "a.txt");

System.out.println(path1); // "dir"
System.out.println(path2); // "dir\a.txt"
System.out.println(path1.compareTo(path2)); // -6
System.out.println(path2.compareTo(path1)); // 6
final var path1 = Path.of("dir", "a.txt");
final var path2 = Path.of("dir", "dir2", "..", "a.txt");

System.out.println(path1); // "dir\a.txt"
System.out.println(path2); // "dir\dir2\..\a.txt"
System.out.println(path1.compareTo(path2)); // -3
System.out.println(path2.compareTo(path1)); // 3

final var path3 = path2.normalize();
System.out.println(path3); // "dir\a.txt"
System.out.println(path1.compareTo(path3)); // 0

default boolean endsWith (String other)

このパスが、endsWith(Path)メソッドで指定されたとおりの方法で指定のパス文字列を変換することで構築される、Pathで終わるかどうかをテストします。

final var path = Path.of("foo", "bar");
System.out.println(path); // "foo\bar"

System.out.println(path.endsWith("r")); // false
System.out.println(path.endsWith("ar")); // false
System.out.println(path.endsWith("bar")); // true
System.out.println(path.endsWith("\\bar")); // false
System.out.println(path.endsWith("o\\bar")); // false
System.out.println(path.endsWith("oo\\bar")); // false
System.out.println(path.endsWith("foo\\bar")); // true
System.out.println(path.endsWith("Zfoo\\bar")); // false

boolean endsWith (Path other)

このパスが、指定されたパスで終わるかどうかをテストします。

final var path = Path.of("foo", "bar");
System.out.println(path); // "foo\bar"

System.out.println(path.endsWith(Path.of("r"))); // false
System.out.println(path.endsWith(Path.of("ar"))); // false
System.out.println(path.endsWith(Path.of("bar"))); // true
System.out.println(path.endsWith(Path.of("o", "bar"))); // false
System.out.println(path.endsWith(Path.of("oo", "bar"))); // false
System.out.println(path.endsWith(Path.of("foo", "bar"))); // true
System.out.println(path.endsWith(Path.of("Z", "foo", "bar"))); // false

boolean equals (Object other)

このパスが指定されたオブジェクトと等しいかどうかをテストします。

System.out.println(System.getProperty("os.name")); // Windows 10

final var path = Path.of("aaa.txt");
System.out.println(path); // "aaa.txt"

// Windows は大文字小文字の区別はありません。
System.out.println(path.equals(Path.of("aaa.txt"))); // true
System.out.println(path.equals(Path.of("AAA.TXT"))); // true
System.out.println(path.equals(Path.of("bbb.txt"))); // false
final var path = Path.of("dir", "aaa.txt");
System.out.println(path); // "dir\aaa.txt"

System.out.println(path.equals(Path.of("dir", "aaa.txt"))); // true
System.out.println(path.equals(Path.of("DIR", "AAA.TXT"))); // true
System.out.println(path.equals(Path.of("aaa.txt"))); // false
System.out.println(path.equals(Path.of("dir"))); // false
System.out.println(path.equals(Path.of("dir", "bbb.txt"))); // false
System.out.println(path.equals(Path.of("xxx", "aaa.txt"))); // false

Path getFileName ()

このパスが示すファイルまたはディレクトリの名前をPathオブジェクトとして返します。

final var path1 = Path.of("dir");
System.out.println(path1); // "dir"
System.out.println(path1.getFileName()); // "dir"

final var path2 = Path.of("dir", "aaa.txt");
System.out.println(path2); // "dir\aaa.txt"
System.out.println(path2.getFileName()); // "aaa.txt"

final var path3 = Path.of("dir", "dir2", "aaa.txt");
System.out.println(path3); // "dir\dir2\aaa.txt"
System.out.println(path3.getFileName()); // "aaa.txt"

final var path4 = Path.of("D:");
System.out.println(path4); // "D:"
System.out.println(path4.getFileName()); // null

final var path5 = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path5); // "D:\java-work\aaa.txt"
System.out.println(path5.getFileName()); // "aaa.txt"

final var path6 = Path.of("..");
System.out.println(path6); // ".."
System.out.println(path6.getFileName()); // ".."

FileSystem getFileSystem ()

このオブジェクトを作成したファイル・システムを返します。

関連 : FileSystem (Java SE 22 & JDK 22)

System.out.println(System.getProperty("os.name")); // Windows 10

final var path = Path.of("aaa.txt");
System.out.println(path); // "aaa.txt"

final var fileSystem = path.getFileSystem();
System.out.println(fileSystem); // sun.nio.fs.WindowsFileSystem@2657d4dd

Path getName (int index)

このパスの名前要素をPathオブジェクトとして返します。

final var path1 = Path.of("dir1", "dir2", "aaa.txt");
System.out.println(path1); // "dir1\dir2\aaa.txt"

//path1.getName(-1); // IllegalArgumentException
System.out.println(path1.getName(0)); // "dir1"
System.out.println(path1.getName(1)); // "dir2"
System.out.println(path1.getName(2)); // "aaa.txt"
//path1.getName(3); // IllegalArgumentException

final var path2 = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path2); // "D:\java-work\aaa.txt"
System.out.println(path2.getName(0)); // "java-work"
System.out.println(path2.getName(1)); // "aaa.txt"
//path2.getName(2); // IllegalArgumentException

final var path3 = Path.of("aaa.txt");
System.out.println(path3); // "aaa.txt"
System.out.println(path3.getName(0)); // "aaa.txt"

final var path4 = Path.of("dir", "..", ".", "aaa.txt");
System.out.println(path4); // "dir\..\.\aaa.txt"
System.out.println(path4.getName(0)); // "dir"
System.out.println(path4.getName(1)); // ".."
System.out.println(path4.getName(2)); // "."
System.out.println(path4.getName(3)); // "aaa.txt"

int getNameCount ()

パス内の名前要素の数を返します。

final var path1 = Path.of("dir1", "dir2", "aaa.txt");
System.out.println(path1); // "dir1\dir2\aaa.txt"
System.out.println(path1.getNameCount()); // 3

final var path2 = Path.of("D:");
System.out.println(path2); // "D:"
System.out.println(path2.getNameCount()); // 0

final var path3 = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path3); // "D:\java-work\aaa.txt"
System.out.println(path3.getNameCount()); // 2

final var path4 = Path.of("aaa.txt");
System.out.println(path4); // "aaa.txt"
System.out.println(path4.getNameCount()); // 1

final var path5 = Path.of("dir", "..", ".", "aaa.txt");
System.out.println(path5); // "dir\..\.\aaa.txt"
System.out.println(path5.getNameCount()); // 4

Path getParent ()

親のパスを返します。このパスが親を持たない場合はnullを返します。

final var path1 = Path.of("dir1", "dir2", "aaa.txt");
System.out.println(path1); // "dir1\dir2\aaa.txt"
System.out.println(path1.getParent()); // "dir1\dir2"
System.out.println(path1.getParent().getParent()); // "dir1"
System.out.println(path1.getParent().getParent().getParent()); // null

final var path2 = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path2); // "D:\java-work\aaa.txt"
System.out.println(path2.getParent()); // "D:\java-work"
System.out.println(path2.getParent().getParent()); // "D:\"
System.out.println(path2.getParent().getParent().getParent()); // null

final var path3 = Path.of("aaa.txt");
System.out.println(path3); // "aaa.txt"
System.out.println(path3.getParent()); // null

final var path4 = Path.of("dir", "..", ".", "aaa.txt");
System.out.println(path4); // "dir\..\.\aaa.txt"
System.out.println(path4.getParent()); // "dir\..\."
System.out.println(path4.getParent().getParent()); // "dir\.."
System.out.println(path4.getParent().getParent().getParent()); // "dir"
System.out.println(path4.getParent().getParent().getParent().getParent()); // null

Path getRoot ()

このパスのルート・コンポーネントをPathオブジェクトとして返します。このパスがルート・コンポーネントを持たない場合はnullを返します。

final var path1 = Path.of("dir1", "dir2", "aaa.txt");
System.out.println(path1); // "dir1\dir2\aaa.txt"
System.out.println(path1.getRoot()); // null

final var path2 = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path2); // "D:\java-work\aaa.txt"
System.out.println(path2.getRoot()); // "D:\"

final var path3 = Path.of("aaa.txt");
System.out.println(path3); // "aaa.txt"
System.out.println(path3.getRoot()); // null

final var path4 = Path.of("dir", "..", ".", "aaa.txt");
System.out.println(path4); // "dir\..\.\aaa.txt"
System.out.println(path4.getRoot()); // null

int hashCode ()

このパスのハッシュ・コードを計算します。

System.out.println(System.getProperty("os.name")); // Windows 10

// Windows は大文字小文字の区別はありません。
System.out.println(Path.of("aaa.txt").hashCode()); // -519425277
System.out.println(Path.of("AAA.TXT").hashCode()); // -519425277
System.out.println(Path.of("dir1", "dir2", "aaa.txt").hashCode()); // 1707759364
System.out.println(Path.of("D:", "java-work", "aaa.txt").hashCode()); // 1186026781

boolean isAbsolute ()

このパスが絶対かどうかを通知します。

final var path1 = Path.of("dir1", "dir2", "aaa.txt");
System.out.println(path1); // "dir1\dir2\aaa.txt"
System.out.println(path1.isAbsolute()); // false

final var path2 = Path.of("D:");
System.out.println(path2); // "D:"
System.out.println(path2.isAbsolute()); // false

final var path3 = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path3); // "D:\java-work\aaa.txt"
System.out.println(path3.isAbsolute()); // true

final var path4 = Path.of("aaa.txt");
System.out.println(path4); // "aaa.txt"
System.out.println(path4.isAbsolute()); // false

final var path5 = Path.of("dir", "..", ".", "aaa.txt");
System.out.println(path5); // "dir\..\.\aaa.txt"
System.out.println(path5.isAbsolute()); // false

default Iterator<Path> iterator ()

このパスの名前要素を処理するイテレータを返します。

final var path = Path.of("dir1", "dir2", "aaa.txt");
System.out.println(path); // "dir1\dir2\aaa.txt"

final var it = path.iterator();

System.out.println("-- forEachRemaining --");
it.forEachRemaining(System.out::println);

// 結果
// ↓
//-- forEachRemaining --
//dir1
//dir2
//aaa.txt
final var path = Path.of("D:");
System.out.println(path); // "D:"

final var it = path.iterator();

System.out.println("-- forEachRemaining --");
it.forEachRemaining(System.out::println);

// 結果
// ↓
//-- forEachRemaining --
final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // "D:\java-work\aaa.txt"

final var it = path.iterator();

System.out.println("-- forEachRemaining --");
it.forEachRemaining(System.out::println);

// 結果
// ↓
//-- forEachRemaining --
//java-work
//aaa.txt
final var path = Path.of("aaa.txt");
System.out.println(path); // "aaa.txt"

final var it = path.iterator();

System.out.println("-- forEachRemaining --");
it.forEachRemaining(System.out::println);

// 結果
// ↓
//-- forEachRemaining --
//aaa.txt
final var path = Path.of("dir", "..", ".", "aaa.txt");
System.out.println(path); // "dir\..\.\aaa.txt"

final var it = path.iterator();

System.out.println("-- forEachRemaining --");
it.forEachRemaining(System.out::println);

// 結果
// ↓
//-- forEachRemaining --
//dir
//..
//.
//aaa.txt

Path normalize ()

このパスから冗長な名前要素を削除したパスを返します。

final var path1 = Path.of("dir1", "dir2", "aaa.txt");
System.out.println(path1); // "dir1\dir2\aaa.txt"
System.out.println(path1.normalize()); // "dir1\dir2\aaa.txt"

final var path2 = Path.of("dir1", "dir2", "..", "aaa.txt");
System.out.println(path2); // "dir1\dir2\..\aaa.txt"
System.out.println(path2.normalize()); // "dir1\aaa.txt"

final var path3 = Path.of("dir1", "dir2", "..", "..", "aaa.txt");
System.out.println(path3); // "dir1\dir2\..\..\aaa.txt"
System.out.println(path3.normalize()); // "aaa.txt"

final var path4 = Path.of("dir1", "dir2", "..", "..", "..", "aaa.txt");
System.out.println(path4); // "dir1\dir2\..\..\..\aaa.txt"
System.out.println(path4.normalize()); // "..\aaa.txt"

final var path5 = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path5); // "D:\java-work\aaa.txt"
System.out.println(path5.normalize()); // "D:\java-work\aaa.txt"

final var path6 = Path.of("D:", "java-work", "..", "aaa.txt");
System.out.println(path6); // "D:\java-work\..\aaa.txt"
System.out.println(path6.normalize()); // "D:\aaa.txt"

final var path7 = Path.of("D:", "java-work", "..", "..", "aaa.txt");
System.out.println(path7); // "D:\java-work\..\..\aaa.txt"
System.out.println(path7.normalize()); // "D:\aaa.txt"

static Path of (String first, String... more)

パス文字列、または結合時にパス文字列を形成する文字列のシーケンスを変換することにより、Pathを返します。

final var path1 = Path.of("dir1", "dir2", "aaa.txt");
System.out.println(path1); // "dir1\dir2\aaa.txt"

final var path2 = Path.of("D:");
System.out.println(path2); // "D:"

final var path3 = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path3); // "D:\java-work\aaa.txt"

final var path4 = Path.of("aaa.txt");
System.out.println(path4); // "aaa.txt"

final var path5 = Path.of("dir", "..", ".", "aaa.txt");
System.out.println(path5); // "dir\..\.\aaa.txt"

static Path of (URI uri)

URIを変換することによってPathを返します。

final var uri = URI.create("file:///D:/java-work/aaa.txt");
System.out.println(uri); // "file:///D:/java-work/aaa.txt"

final var path = Path.of(uri);
System.out.println(path); // "D:\java-work\aaa.txt"
final var uri = URI.create("http://example.com");
System.out.println(uri); // "http://example.com"

try {
    final var path = Path.of(uri);
} catch (FileSystemNotFoundException e) {
    System.out.println(e);
}

// 結果
// ↓
//java.nio.file.FileSystemNotFoundException: Provider "http" not installed

default WatchKey register (WatchService watcher, WatchEvent.Kind<?>... events)

このパスで検出されたファイルを監視サービスに登録します。

try (final var executor = Executors.newSingleThreadScheduledExecutor()) {

    final var targetDir = Path.of("D:", "java-work");
    System.out.println(targetDir); // "D:\java-work"

    // まずファイルが存在しない状態とします。
    final var targetFile = targetDir.resolve("aaa.txt");
    System.out.println(targetFile); // "D:\java-work\aaa.txt"
    System.out.println(Files.exists(targetFile)); // false

    // 3秒後にファイルを作成します。
    executor.schedule(() -> {
        try {
            Files.createFile(targetFile);
        } catch (IOException e) {
            System.out.println("IOException!");
        }
    }, 3, TimeUnit.SECONDS);

    try (final var watchService = FileSystems.getDefault().newWatchService()) {

        final var watchKey = targetDir.register(watchService, ENTRY_CREATE);

        // イベントが発生するまで待機。
        final var takeKey = watchService.take();
        System.out.println(watchKey.equals(takeKey)); // true

        final var contexts = takeKey.pollEvents().stream()
                .map(WatchEvent::context)
                .toList();
        System.out.println(contexts); // [aaa.txt]
        System.out.println(Files.exists(targetFile)); // true
    }
}

WatchKey register (WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers)

このパスで検出されたファイルを監視サービスに登録します。

関連 :

Path relativize (Path other)

このパスと指定されたパスとの間の相対パスを構築します。

final var path = Path.of("D:", "java-work");
System.out.println(path); // "D:\java-work"

final var ret1 = path.relativize(Path.of("D:", "java-work", "aaa.txt"));
System.out.println(ret1); // "aaa.txt"

final var ret2 = path.relativize(Path.of("D:", "java-work", "dir", "bbb.txt"));
System.out.println(ret2); // "dir\bbb.txt"
final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // "D:\java-work\aaa.txt"

final var ret1 = path.relativize(Path.of("D:", "java-work"));
System.out.println(ret1); // ".."

final var ret2 = path.relativize(Path.of("D:", "xxx", "ccc.txt"));
System.out.println(ret2); // "..\..\xxx\ccc.txt"
final var path = Path.of("dir1", "dir2");
System.out.println(path); // "dir1\dir2"

final var ret1 = path.relativize(Path.of("dir1"));
System.out.println(ret1); // ".."

final var ret2 = path.relativize(Path.of("dir1", "dir2"));
System.out.println(ret2); // ""

final var ret3 = Path.of("dir1", "dir2", "aaa.txt");
System.out.println(path.relativize(ret3)); // "aaa.txt"

final var ret4 = path.relativize(Path.of("..", "dir1", "dir2", "aaa.txt"));
System.out.println(ret4); // "..\..\..\dir1\dir2\aaa.txt"

default Path resolve (String other)

指定されたパス文字列をPathに変換してから、resolveメソッドで指定されたとおりの方法で、このPathに対して解決します。

final var path = Path.of("dir1");
System.out.println(path); // "dir1"
System.out.println(path.resolve("dir2")); // "dir1\dir2"
System.out.println(path.resolve("dir2").resolve("aaa.txt")); // "dir1\dir2\aaa.txt"
System.out.println(path.resolve("..")); // "dir1\.."
System.out.println(path.resolve("")); // "dir1"

default Path resolve (String first, String... more)

パス文字列をパスに変換し、そのパスをこのパスに対して解決してから、追加のパス文字列に対して同じプロシージャを繰り返し実行します。

final var path = Path.of("dir1");
System.out.println(path); // "dir1"
System.out.println(path.resolve("dir2")); // "dir1\dir2"
System.out.println(path.resolve("dir2", "aaa.txt")); // "dir1\dir2\aaa.txt"

Path resolve (Path other)

指定されたパスをこのパスに対して解決します。

final var path = Path.of("dir1");
System.out.println(path); // "dir1"
System.out.println(path.resolve(Path.of("aaa.txt"))); // "dir1\aaa.txt"
System.out.println(path.resolve(Path.of("dir2", "dir3"))); // "dir1\dir2\dir3"
System.out.println(path.resolve(Path.of(".."))); // "dir1\.."
System.out.println(path.resolve(Path.of(""))); // "dir1"

final var absolutePath = Path.of("D:", "java-work", "aaa.txt");
System.out.println(absolutePath); // "D:\java-work\aaa.txt"
System.out.println(path.resolve(absolutePath)); // "D:\java-work\aaa.txt"

default Path resolve (Path first, Path... more)

このパスに対してパスを解決してから、追加のパスを繰り返し解決します。

final var dir1 = Path.of("dir1");
System.out.println(dir1); // "dir1"

final var dir2 = Path.of("dir2");
System.out.println(dir2); // "dir2"

final var file = Path.of("aaa.txt");
System.out.println(file); // "aaa.txt"

System.out.println(dir1.resolve(file)); // "dir1\aaa.txt"
System.out.println(dir1.resolve(dir2, file)); // "dir1\dir2\aaa.txt"

default Path resolveSibling (String other)

指定されたパス文字列をPathに変換してから、resolveSiblingメソッドで指定されたとおりの方法で、このパスの親パスに対して解決します。

final var path = Path.of("dir1", "dir2", "foo");
System.out.println(path); // "dir1\dir2\foo"
System.out.println(path.resolveSibling("bar")); // "dir1\dir2\bar"
System.out.println(path.resolveSibling("..")); // "dir1\dir2\.."
System.out.println(path.resolveSibling("")); // "dir1\dir2"

default Path resolveSibling (Path other)

指定されたパスをこのパスの親パスに対して解決します。

final var path = Path.of("dir1", "dir2", "foo");
System.out.println(path); // "dir1\dir2\foo"
System.out.println(path.resolveSibling(Path.of("bar"))); // "dir1\dir2\bar"
System.out.println(path.resolveSibling(Path.of("aaa", "bbb"))); // "dir1\dir2\aaa\bbb"
System.out.println(path.resolveSibling(Path.of("..", "bbb"))); // "dir1\dir2\..\bbb"
System.out.println(path.resolveSibling(Path.of(""))); // "dir1\dir2"

final var absolutePath = Path.of("D:", "java-work", "aaa.txt");
System.out.println(absolutePath); // "D:\java-work\aaa.txt"
System.out.println(path.resolveSibling(absolutePath)); // "D:\java-work\aaa.txt"

default boolean startsWith (String other)

このパスが、startsWith(Path)メソッドで指定されたとおりの方法で指定のパス文字列を変換することで構築される、Pathで始まるかどうかをテストします。

final var path = Path.of("foo", "bar");
System.out.println(path); // "foo\bar"

System.out.println(path.startsWith("f")); // false
System.out.println(path.startsWith("fo")); // false
System.out.println(path.startsWith("foo")); // true
System.out.println(path.startsWith("foo\\")); // true
System.out.println(path.startsWith("foo\\b")); // false
System.out.println(path.startsWith("foo\\ba")); // false
System.out.println(path.startsWith("foo\\bar")); // true
System.out.println(path.startsWith("foo\\barZ")); // false

boolean startsWith (Path other)

このパスが、指定されたパスで始まるかどうかをテストします。

final var path = Path.of("foo", "bar");
System.out.println(path); // "foo\bar"

System.out.println(path.startsWith(Path.of("f"))); // false
System.out.println(path.startsWith(Path.of("fo"))); // false
System.out.println(path.startsWith(Path.of("foo"))); // true
System.out.println(path.startsWith(Path.of("foo", "b"))); // false
System.out.println(path.startsWith(Path.of("foo", "ba"))); // false
System.out.println(path.startsWith(Path.of("foo", "bar"))); // true
System.out.println(path.startsWith(Path.of("foo", "bar", "Z"))); // false

Path subpath (int beginIndex, int endIndex)

このパスの名前要素のサブシーケンスである相対Pathを返します。

final var path1 = Path.of("dir1", "dir2", "aaa.txt");
System.out.println(path1); // "dir1\dir2\aaa.txt"

//path1.subpath(0, 0); // IllegalArgumentException
System.out.println(path1.subpath(0, 1)); // "dir1"
System.out.println(path1.subpath(0, 2)); // "dir1\dir2"
System.out.println(path1.subpath(0, 3)); // "dir1\dir2\aaa.txt"
//path1.subpath(0, 4); // IllegalArgumentException
//path1.subpath(1, 1); // IllegalArgumentException
System.out.println(path1.subpath(1, 2)); // "dir2"
System.out.println(path1.subpath(1, 3)); // "dir2\aaa.txt"
System.out.println(path1.subpath(2, 3)); // "aaa.txt"

final var path2 = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path2); // "D:\java-work\aaa.txt"

System.out.println(path2.subpath(0, 1)); // "java-work"
System.out.println(path2.subpath(0, 2)); // "java-work\aaa.txt"
//path2.subpath(0, 3); // IllegalArgumentException

Path toAbsolutePath ()

このパスの絶対パスを表すPathオブジェクトを返します。

final var userDir = System.getProperty("user.dir");
System.out.println(userDir); // "D:\java-work"

final var path1 = Path.of("aaa.txt");
System.out.println(path1); // "aaa.txt"
System.out.println(path1.toAbsolutePath()); // "D:\java-work\aaa.txt"

final var path2 = Path.of("..", "aaa.txt");
System.out.println(path2); // "..\aaa.txt"
System.out.println(path2.toAbsolutePath()); // "D:\java-work\..\aaa.txt"

final var path3 = Path.of("D:", "xxx", "bbb.txt");
System.out.println(path3); // "D:\xxx\bbb.txt"
System.out.println(path3.toAbsolutePath()); // "D:\xxx\bbb.txt"

default File toFile ()

このパスを表すFileオブジェクトを返します。

final var path = Path.of("D:", "java-work", "aaa.txt");
System.out.println(path); // "D:\java-work\aaa.txt"

final var file = path.toFile();
System.out.println(file); // "D:\java-work\aaa.txt"

System.out.println(file.createNewFile()); // true

Path toRealPath (LinkOption... options)

既存のファイルの実際のパスを返します。

final var userDir = System.getProperty("user.dir");
System.out.println(userDir); // "D:\java-work"

final var path = Path.of("aaa.txt");
System.out.println(path); // "aaa.txt"
System.out.println(Files.exists(path)); // false

try {
    path.toRealPath();
} catch (NoSuchFileException e) {
    System.out.println("NoSuchFileException!");
}

// 結果
// ↓
//NoSuchFileException!

Files.createFile(path);
System.out.println(Files.exists(path)); // true

final var ret = path.toRealPath();
System.out.println(ret); // "D:\java-work\aaa.txt"
final var path = Path.of("D:", "java-work", "aaa.txt");
Files.createFile(path);

final var link = Path.of("D:", "java-work", "link.txt");
Files.createSymbolicLink(link, path);

// --- PowerShell ---
//PS D:\java-work> ls
// ...
//Mode                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//-a---          xxxx/xx/xx    xx:xx              0 aaa.txt
//la---          xxxx/xx/xx    xx:xx              0 link.txt -> D:\java-work\aaa.txt

System.out.println(path); // "D:\java-work\aaa.txt"
System.out.println(path.toRealPath()); // "D:\java-work\aaa.txt"
System.out.println(path.toRealPath(LinkOption.NOFOLLOW_LINKS)); // "D:\java-work\aaa.txt"

System.out.println(link); // "D:\java-work\link.txt"
System.out.println(link.toRealPath()); // "D:\java-work\aaa.txt"
System.out.println(link.toRealPath(LinkOption.NOFOLLOW_LINKS)); // "D:\java-work\link.txt"
// Windows は大文字小文字の区別はありません。
final var path = Path.of("D:", "java-work", "aaa.txt");
Files.createFile(path);

final var path2 = Path.of("D:", "java-work", "AAA.TXT");
System.out.println(path2); // "D:\java-work\AAA.TXT"
System.out.println(path2.toRealPath()); // "D:\java-work\aaa.txt"

String toString ()

このパスの文字列表現を返します。

final var path1 = Path.of("dir1", "dir2", "aaa.txt");
final var str1 = path1.toString();
System.out.println(str1); // "dir1\dir2\aaa.txt"

final var path2 = Path.of("D:");
final var str2 = path2.toString();
System.out.println(str2); // "D:"

final var path3 = Path.of("D:", "java-work", "aaa.txt");
final var str3 = path3.toString();
System.out.println(str3); // "D:\java-work\aaa.txt"

final var path4 = Path.of("aaa.txt");
final var str4 = path4.toString();
System.out.println(str4); // "aaa.txt"

URI toUri ()

このパスを表すURIを返します。

final var userDir = System.getProperty("user.dir");
System.out.println(userDir); // "D:\java-work"

final var path1 = Path.of("aaa.txt");
System.out.println(path1); // "aaa.txt"
System.out.println(path1.toUri()); // "file:///D:/java-work/aaa.txt"

final var path2 = Path.of("dir1", "dir2", "aaa.txt");
System.out.println(path2); // "dir1\dir2\aaa.txt"
System.out.println(path2.toUri()); // "file:///D:/java-work/dir1/dir2/aaa.txt"

final var path3 = Path.of("D:");
System.out.println(path3); // "D:"
System.out.println(path3.toUri()); // "file:///D:/"

final var path4 = Path.of("D:", "xxx", "aaa.txt");
System.out.println(path4); // "D:\xxx\aaa.txt"
System.out.println(path4.toUri()); // "file:///D:/xxx/aaa.txt"

Iterableで宣言されたメソッド

forEach, spliterator

Java API 使用例 : Iterable」をご参照ください。


関連記事

ページの先頭へ