0
0

More than 1 year has passed since last update.

【JavaGold】NIO.2①

Last updated at Posted at 2023-07-24

概要

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クラスを使用する。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0