ファイルとディレクトリの操作

Javaのファイル入出力(I/O)において、「ファイルとディレクトリの操作」は、ファイルシステムと連携し、ファイルの作成・削除・読み書き・ディレクトリの管理などを行う重要な機能です。Javaでは主に java.io パッケージおよび java.nio.file パッケージが使用されます。以下では、それぞれの操作について詳しく説明します。


1. File クラス(java.io.File

概要:

File クラスは、ファイルやディレクトリのパス名を表すオブジェクトを提供します。ただし、実際のファイル内容を読み書きする機能は持ちません。

主な操作:

ファイルまたはディレクトリの作成:

java
File file = new File("example.txt"); file.createNewFile(); // ファイルが存在しなければ新規作成
java
File dir = new File("exampleDir"); dir.mkdir(); // ディレクトリを作成

存在確認、読み取り・書き込み権限の確認:

java
file.exists(); // 存在確認 file.canRead(); // 読み取り可能か file.canWrite(); // 書き込み可能か

削除:

java
file.delete(); // ファイルまたは空のディレクトリを削除

情報の取得:

java
file.getName(); // ファイル名 file.getPath(); // パス file.length(); // サイズ(バイト) file.isDirectory(); // ディレクトリか

ディレクトリ内のファイル一覧取得:

java
File dir = new File("exampleDir"); String[] files = dir.list(); for (String name : files) { System.out.println(name); }

2. java.nio.file パッケージ(Java 7以降)

概要:

よりモダンで柔軟なファイル操作が可能です。Path, Files, Paths などのクラスを使用します。

主な操作:

ファイルまたはディレクトリの作成:

java
Path filePath = Paths.get("newFile.txt"); Files.createFile(filePath); Path dirPath = Paths.get("newDir"); Files.createDirectory(dirPath);

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

java
Files.copy(Paths.get("source.txt"), Paths.get("dest.txt"), StandardCopyOption.REPLACE_EXISTING); Files.move(Paths.get("old.txt"), Paths.get("new.txt"), StandardCopyOption.REPLACE_EXISTING); Files.delete(Paths.get("fileToDelete.txt"));

ファイルの存在確認:

java
Files.exists(Paths.get("someFile.txt"));

ディレクトリ内のファイル一覧(ストリーム使用):

java
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("exampleDir"))) { for (Path entry : stream) { System.out.println(entry.getFileName()); } }

ファイル属性の取得:

java
BasicFileAttributes attrs = Files.readAttributes(Paths.get("example.txt"), BasicFileAttributes.class); System.out.println("作成日時: " + attrs.creationTime()); System.out.println("サイズ: " + attrs.size());

3. ファイルパスの注意点

  • 相対パスと絶対パスの使い分けに注意が必要です。

  • OS依存の区切り文字(/ vs \)の違いには、Paths.get()File.separator を使うと安全です。


まとめ

操作 java.io.File java.nio.file(推奨)
ファイル/ディレクトリの作成 createNewFile(), mkdir() Files.createFile(), createDirectory()
存在確認 exists() Files.exists()
削除 delete() Files.delete()
コピー・移動 手動処理が必要 Files.copy(), Files.move()
属性取得 限定的なメソッドのみ Files.readAttributes()

java.nio.file パッケージは、非同期処理や属性管理などを含むより高機能なAPIであり、現在のJavaプログラムではこちらの利用が推奨されます。

生成日:2025/05/03