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 クラスのよく使うメソッドです:
1、ファイル操作
ファイルの読み書き
例
// ファイルのすべての行を読み取る
List<String> lines = Files.readAllLines(path);
// ファイルに書き込む
Files.write(path, content.getBytes());
// 追記書き込み
Files.write(path, content.getBytes(), StandardOpenOption.APPEND);
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);
Files.copy(sourcePath, targetPath);
// ファイルを移動/名前変更
Files.move(sourcePath, targetPath);
// ファイルを削除
Files.delete(path);
2、ディレクトリ操作
ディレクトリの作成
例
// 単一レベルのディレクトリを作成
Files.createDirectory(path);
// 複数レベルのディレクトリを作成
Files.createDirectories(path);
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);
}
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);
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);
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);
}
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");
Path tempFile = Files.createTempFile("prefix", ".suffix");
// 一時ディレクトリを作成
Path tempDir = Files.createTempDirectory("tempDir");
3、ファイル属性ビュー
例
// ファイルの所有者を取得
UserPrincipal owner = Files.getOwner(path);
// ファイルのストレージ情報を取得
FileStore store = Files.getFileStore(path);
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());
}
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);
} // ストリームを自動的に閉じる
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クラスの代わりにこれを使用することを推奨します。