概要
java.nio.file.Paths
クラスのresolve()
メソッドは、2つのPath
インスタンスを結合して新しいPath
インスタンスを作成する。
このメソッドは、パスの絶対・相対の関係にかかわらず、2つのパスを連結して新しいパスを作成する。
シグネチャは以下のようになっている。
public Path resolve(Path other)
引数として結合したいもう一方のPath
インスタンス(other
)を受け取り、それらを結合した新しいPath
インスタンスを返す。
例
例えば、次のようなディレクトリ構造があったとする。
root
├── dir1
│ └── file1.txt
└── dir2
└── file2.txt
以下は、Paths.resolve()
メソッドを使用して2つのPath
インスタンスを結合している。
import java.nio.file.Path;
import java.nio.file.Paths;
public class ResolveExample {
public static void main(String[] args) {
Path dirPath = Paths.get("root/dir1");
Path filePath = Paths.get("root/dir2/file2.txt");
// ディレクトリパスとファイルパスを結合して新しいパスを作成
Path resolvedPath = dirPath.resolve(filePath);
System.out.println("結合されたパス: " + resolvedPath);
}
}
この例では、Paths.get()
メソッドを使って2つのPath
インスタンス(dirPath
とfilePath
)を作成している。dirPath.resolve(filePath)
を呼び出すことで、dirPath
とfilePath
を結合して新しいPath
インスタンスを作成し、結合されたパスを出力している。
実行結果
結合されたパス: root/dir1/root/dir2/file2.txt
resolve()
メソッドにより、dirPath
とfilePath
が結合されて新しいパスが作成されていることがわかる。