Java NIO Files クラス

java.nio.file.Filesは Java NIO (New I/O) パッケージ内のユーティリティクラスであり、java.nio.fileパッケージ内にあります。

java.nio.file.Filesファイルシステム内のファイルやディレクトリを操作するための一連の静的メソッドを提供し、ファイル I/O 操作を大幅に簡素化します。

主な特徴

  • 静的メソッド:すべてのメソッドが静的であるため、インスタンスを作成する必要はありません
  • 豊富な機能:ファイルの読み書き、属性操作、ディレクトリ走査など、さまざまな機能を提供します
  • 例外処理:一貫して使用し、IOExceptionファイル操作の例外を処理します
  • Path との連携:主にjava.nio.file.Pathインターフェースと一緒に使用します

よく使うメソッドの分類

注意:多くのメソッドは IOException をスローするため、使用時には例外処理が必要です。

以下は java.nio.file.Files クラスのよく使うメソッドです:

メソッド 説明
ファイル操作
static Path copy(Path source, Path target, CopyOption... options) ファイルをソースパスからターゲットパスにコピーします
static Path move(Path source, Path target, CopyOption... options) ファイルを移動または名前変更します
static void delete(Path path) ファイルを削除します
static boolean deleteIfExists(Path path) ファイルが存在する場合は削除します
ファイル属性
static boolean exists(Path path, LinkOption... options) ファイルが存在するか確認します
static boolean isDirectory(Path path, LinkOption... options) パスがディレクトリかどうか確認します
static boolean isRegularFile(Path path, LinkOption... options) パスが通常のファイルかどうか確認します
static boolean isReadable(Path path) ファイルが読み取り可能かどうか確認します
static boolean isWritable(Path path) ファイルが書き込み可能かどうか確認します
static boolean isExecutable(Path path) ファイルが実行可能かどうか確認します
static long size(Path path) ファイルサイズ(バイト)を返します
static FileTime getLastModifiedTime(Path path, LinkOption... options) ファイルの最終更新時刻を取得します
ファイル内容の操作
static byte[] readAllBytes(Path path) ファイルのすべてのバイトを読み取ります
static List<String> readAllLines(Path path) ファイルのすべての行を読み取ります
static List<String> readAllLines(Path path, Charset cs) 指定された文字セットでファイルのすべての行を読み取ります
static Stream<String> lines(Path path) ファイル内の行のストリームを返します
static Stream<String> lines(Path path, Charset cs) 指定された文字セットでファイル内の行のストリームを返します
static Path write(Path path, byte[] bytes, OpenOption... options) バイトをファイルに書き込みます
static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options) テキスト行をファイルに書き込みます
ディレクトリ操作
static Stream<Path> list(Path dir) ディレクトリ内のエントリを一覧表示します
static DirectoryStream<Path> newDirectoryStream(Path dir) ディレクトリストリームを開きます
static Path createDirectory(Path dir, FileAttribute<?>... attrs) ディレクトリを作成します
static Path createDirectories(Path dir, FileAttribute<?>... attrs) ディレクトリを作成します(存在しない親ディレクトリもすべて含む)
一時ファイル/ディレクトリ
static Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs) 一時ファイルを作成します
static Path createTempDirectory(Path dir, String prefix, FileAttribute<?>... attrs) 一時ディレクトリを作成します
その他
static Path createFile(Path path, FileAttribute<?>... attrs) 新しいファイルを作成します
static SeekableByteChannel newByteChannel(Path path, OpenOption... options) ファイルを開くか作成し、シーク可能なバイトチャネルを返します
static InputStream newInputStream(Path path, OpenOption... options) ファイル入力ストリームを開きます
static OutputStream newOutputStream(Path path, OpenOption... options) ファイル出力ストリームを開きます
static BufferedReader newBufferedReader(Path path) バッファ付きリーダーを開きます
static BufferedWriter newBufferedWriter(Path path, OpenOption... options) バッファ付きライターを開きます
static String probeContentType(Path path) ファイルのコンテンツタイプを調べます

1、ファイル操作

ファイルの読み書き

例

// ファイルのすべての行を読み取る
List<String> lines = Files.readAllLines(path);

// ファイルに書き込む
Files.write(path, content.getBytes());

// 追記書き込み
Files.write(path, content.getBytes(), StandardOpenOption.APPEND);

ファイルのコピー/移動/削除

例

// ファイルをコピー
Files.copy(sourcePath, targetPath);

// ファイルを移動/名前変更
Files.move(sourcePath, targetPath);

// ファイルを削除
Files.delete(path);

2、ディレクトリ操作

ディレクトリの作成

例

// 単一レベルのディレクトリを作成
Files.createDirectory(path);

// 複数レベルのディレクトリを作成
Files.createDirectories(path);

ディレクトリの走査

例

// ディレクトリを走査
try (Stream<Path> paths = Files.list(directoryPath)) {
    paths.forEach(System.out::println);
}

// ディレクトリを再帰的に走査
try (Stream<Path> paths = Files.walk(directoryPath)) {
    paths.forEach(System.out::println);
}

3、ファイル属性操作

ファイル属性の取得

例

// ファイルが存在するか確認
boolean exists = Files.exists(path);

// ファイルサイズを取得
long size = Files.size(path);

// ファイルの最終更新時刻を取得
FileTime lastModifiedTime = Files.getLastModifiedTime(path);

ファイル属性の設定

例

// ファイルの最終更新時刻を設定
Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis()));

// ファイルの権限を設定
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-x---");
Files.setPosixFilePermissions(path, perms);

高度な機能

1、ファイル検索

例

// 特定の拡張子のファイルを検索
try (Stream<Path> paths = Files.find(
        directoryPath,
        Integer.MAX_VALUE,
        (path, attrs) -> path.toString().endsWith(".txt"))) {
    paths.forEach(System.out::println);
}

2、一時ファイル操作

例

// 一時ファイルを作成
Path tempFile = Files.createTempFile("prefix", ".suffix");

// 一時ディレクトリを作成
Path tempDir = Files.createTempDirectory("tempDir");

3、ファイル属性ビュー

例

// ファイルの所有者を取得
UserPrincipal owner = Files.getOwner(path);

// ファイルのストレージ情報を取得
FileStore store = Files.getFileStore(path);

ベストプラクティス

例外処理

例

try {
    Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    System.err.println("ファイル操作に失敗しました: " + e.getMessage());
}

2、リソースのクリーンアップ

例

try (Stream<String> lines = Files.lines(path)) {
    lines.forEach(System.out::println);
} // ストリームを自動的に閉じる

3、パフォーマンスの考慮

  • 大きなファイルにはバッファ付きストリームを使用します (Files.newBufferedReader/Files.newBufferedWriter)
  • バッチ操作時には、使用を検討し、Files.walk再帰呼び出しは使用しません
  • 頻繁にアクセスする属性はキャッシュできます

従来の I/O との比較

特性 Files クラス (NIO) 従来の I/O (java.io)
メソッドのタイプ 静的メソッド インスタンスメソッド
パス表現 Path インターフェースを使用 File クラスを使用
例外処理 IOException を一貫して使用 さまざまな例外タイプ
機能の豊富さ より豊富な機能 基本的な機能
シンボリックリンクの処理 ネイティブサポート 限定的なサポート
ファイル属性の操作 より包括的 限定的

クラスを通じて、FilesJava はより現代的で強力なファイル操作 API を提供しており、新しいプロジェクトでは従来のjava.io.Fileクラスの代わりにこれを使用することを推奨します。

その他の拡張