概要
Java SE 7から導入された、新しいI/O(Input/Output)APIのひとつである。
NIO.2(JSR 203: More New I/O APIs for the Java Platform)は、従来のJava I/O API(java.io
パッケージ)よりも高度なI/O操作をサポートしている。
NIO.2ではファイルやディレクトリへのパスを表すjava.nio.file.Path
インタフェースを使用する。
主なメソッド
-
static Path get(String first, String... more)
:
指定された文字列からパスを作成する。 -
Path getParent()
:
パスの親ディレクトリを返す。 -
Path getFileName()
:
パスのファイル名部分を返す。 -
toAbsolutePath()
:
絶対パスを取得して返す。 -
Path resolve(Path other)
:
他のパスと結合して新しいパスを作成する。 -
Path normalize()
:
パスを正規化する。不要な要素を除去し、相対パスを絶対パスに変換する。 -
File toFile()
:
File
オブジェクトに変換する。 -
boolean isAbsolute()
:
パスが絶対パスかを判定する。 -
boolean startsWith(Path other)
:
他のパスで始まるかを判定する。 -
boolean endsWith(Path other)
:
他のパスで終わるかを判定する。
例
import java.nio.file.FileSystems;
import java.nio.file.Path;
public class PathExample {
public static void main(String[] args) {
// パスを構築する例
Path path = FileSystems.getDefault().getPath("C:\\Users\\user\\Documents\\example.txt");
System.out.println("パス: " + path);
// 親ディレクトリを取得する例
Path parentPath = path.getParent();
System.out.println("親ディレクトリ: " + parentPath);
// ファイル名を取得する例
Path fileName = path.getFileName();
System.out.println("ファイル名: " + fileName);
// 別のパスと結合する例
Path anotherPath = FileSystems.getDefault().getPath("C:\\Temp\\test.txt");
Path resolvedPath = path.resolve(anotherPath);
System.out.println("結合されたパス: " + resolvedPath);
// パスを正規化する例
Path normalizedPath = path.normalize();
System.out.println("正規化されたパス: " + normalizedPath);
// パスが絶対パスかどうかを判定する例
boolean isAbsolute = path.isAbsolute();
System.out.println("絶対パスかどうか: " + isAbsolute);
// 別のパスで始まるかどうかを判定する例
boolean startsWith = path.startsWith(FileSystems.getDefault().getPath("C:\\Users\\user"));
System.out.println("指定したパスで始まるかどうか: " + startsWith);
// 別のパスで終わるかどうかを判定する例
boolean endsWith = path.endsWith(FileSystems.getDefault().getPath("example.txt"));
System.out.println("指定したパスで終わるかどうか: " + endsWith);
}
}
実行結果
パス: C:\Users\user\Documents\example.txt
親ディレクトリ: C:\Users\user\Documents
ファイル名: example.txt
結合されたパス: C:\Users\user\Documents\example.txt\C:\Temp\test.txt
正規化されたパス: C:\Users\user\Documents\example.txt
絶対パスかどうか: true
指定したパスで始まるかどうか: true
指定したパスで終わるかどうか: true
このように、java.nio.file.Path
インタフェースはこれまでの
java.io.File
クラスが担っていた、ファイルやディレクトリのパス表現の部分を分離した機能を持っていることがわかる。
また、ファイル操作をするには、同じくNIO.2のjava.nio.file.Files
クラスを使用する。