java.io.File
クラスとは?
ファイルやディレクトリのパス情報を表すクラスです。
実際のファイルの読み書きではなく、**ファイルやディレクトリの操作(存在確認・作成・削除など)**を行うために使います。
- パッケージ:
java.io
- 実体:ファイル、ディレクトリの両方を扱える
コンストラクタ(生成方法)
File file1 = new File("test.txt"); // 相対パス
File file2 = new File("/path/to/file.txt"); // 絶対パス
File file3 = new File("dir", "file.txt"); // 親 + 子
File parent = new File("/path/to");
File file4 = new File(parent, "file.txt"); // 親File + 子
よく使うメソッド一覧
メソッド名 |
戻り値 |
説明 |
exists() |
boolean |
ファイル or ディレクトリが存在するか |
isFile() |
boolean |
実体がファイルか |
isDirectory() |
boolean |
実体がディレクトリか |
createNewFile() |
boolean |
新しい空のファイルを作成(失敗時 false) |
mkdir() / mkdirs()
|
boolean |
ディレクトリを1階層 or 再帰的に作成 |
delete() |
boolean |
ファイルまたは空のディレクトリを削除 |
getName() |
String |
名前だけ取得(例: "file.txt" ) |
getPath() |
String |
相対パス or 絶対パス |
getAbsolutePath() |
String |
絶対パスを取得 |
getParent() |
String |
親パスの文字列(nullになることも) |
length() |
long |
ファイルのバイトサイズ |
renameTo(File dest) |
boolean |
ファイル名変更や移動 |
list() / listFiles()
|
String[] / File[]
|
ディレクトリ内の一覧を取得 |
使用例
File file = new File("example.txt");
if (!file.exists()) {
file.createNewFile(); // 空のファイルを作成
}
System.out.println("パス: " + file.getAbsolutePath());
System.out.println("サイズ: " + file.length() + "バイト");
注意点
ポイント |
解説 |
File は「実体」ではなく「名前」 |
存在していなくてもFile オブジェクトは作れる |
ファイル内容の読み書きは別クラスで |
例:FileReader , BufferedReader , Files.readAllLines() など |
delete() は非再帰的 |
ディレクトリが空でないと削除できない |
listFiles() などは null を返すことがある |
ディレクトリでない場合やアクセス不可の場合に注意 |
File
→ Path
に変換
File file = new File("sample.txt");
Path path = file.toPath(); // File → Path に変換
java.nio.file.Path
とは?
Java 7 以降で導入された新しいファイルシステムAPIの一部で、パス情報(ファイルやディレクトリ)を表すインターフェースです。
Path の生成方法
import java.nio.file.*;
Path path1 = Paths.get("file.txt"); // 相対パス
Path path2 = Paths.get("/usr", "local", "bin"); // 複数指定
Path path3 = Paths.get("C:\\Users\\me\\file.txt"); // WindowsパスもOK
File file = new File("test.txt");
Path path4 = file.toPath(); // File → Path
主なメソッド一覧
メソッド名 |
戻り値 |
内容 |
toAbsolutePath() |
Path |
絶対パスを取得 |
getFileName() |
Path |
最後の名前(例:file.txt ) |
getParent() |
Path or null
|
親のパス |
getRoot() |
Path or null
|
ルート部分(例:/ や C:\ ) |
isAbsolute() |
boolean |
絶対パスかどうか |
normalize() |
Path |
.. や . を正規化 |
resolve(String) |
Path |
相対パスを結合 |
relativize(Path) |
Path |
2つのパスの相対関係を取得 |
toFile() |
File |
Path → File に変換 |
startsWith(String) / endsWith(String)
|
boolean |
パスの前後の一致を確認 |
使用例
Path path = Paths.get("data", "test.txt");
System.out.println("ファイル名: " + path.getFileName());
System.out.println("親ディレクトリ: " + path.getParent());
System.out.println("絶対パス: " + path.toAbsolutePath());
PathとFileの違い
特徴 |
java.io.File |
java.nio.file.Path |
APIの世代 |
Java 1.0 |
Java 7〜 |
型 |
クラス |
インターフェース |
内容操作 |
パスのみ |
パス操作に特化 |
ファイル操作 |
独自メソッド |
Files クラスを使用 |
高機能操作 |
乏しい |
豊富(コピー、移動、リンクなど) |
変換 |
toPath() |
toFile() |
よく使うパターン
// 親パスに子パスを結合
Path parent = Paths.get("/home/user");
Path full = parent.resolve("document.txt");
// 相対パスへの変換
Path base = Paths.get("/home/user");
Path target = Paths.get("/home/user/images/pic.jpg");
Path relative = base.relativize(target); // → images/pic.jpg
java.nio.file.Files
とは?
Files
は Path
を使ってファイルやディレクトリの**実体操作(作成・読み書き・削除など)**を行うユーティリティクラスです。
- パッケージ:
java.nio.file
- staticメソッドが中心
基本の使い方
Path path = Paths.get("example.txt");
if (!Files.exists(path)) {
Files.createFile(path);
}
List<String> lines = Files.readAllLines(path);
Files.write(path, List.of("Hello", "World"));
主要メソッド一覧
ファイル・ディレクトリの情報取得
メソッド |
戻り値 |
説明 |
exists(Path) |
boolean |
存在確認 |
isDirectory(Path) |
boolean |
ディレクトリか |
isRegularFile(Path) |
boolean |
通常ファイルか |
size(Path) |
long |
ファイルサイズ |
getLastModifiedTime(Path) |
FileTime |
最終更新時刻 |
作成・削除・移動・コピー
メソッド |
戻り値 |
説明 |
createFile(Path) |
Path |
空ファイル作成 |
createDirectory(Path) |
Path |
単層ディレクトリ作成 |
createDirectories(Path) |
Path |
多層ディレクトリ作成 |
delete(Path) |
void |
削除(例外あり) |
deleteIfExists(Path) |
boolean |
存在すれば削除 |
copy(Path, Path, CopyOption...) |
Path |
コピー |
move(Path, Path, CopyOption...) |
Path |
移動またはリネーム |
読み書き(I/O)
メソッド |
戻り値 |
説明 |
readAllLines(Path) |
List<String> |
全行読み込み |
readAllBytes(Path) |
byte[] |
全バイナリ読み込み |
lines(Path) |
Stream<String> |
ストリームで読み込み |
write(Path, List<String>) |
Path |
文字列リストの書き込み |
write(Path, byte[]) |
Path |
バイナリ書き込み |
newBufferedReader(Path) |
BufferedReader |
読み取りストリーム |
newBufferedWriter(Path) |
BufferedWriter |
書き込みストリーム |
その他便利操作
メソッド |
戻り値 |
説明 |
walk(Path) |
Stream<Path> |
再帰的ディレクトリ探索 |
walkFileTree(Path, FileVisitor) |
FileVisitResult |
カスタム処理付き探索 |
isReadable(Path) / isWritable(Path) / isExecutable(Path)
|
boolean |
アクセス権確認 |
使用例:ファイルコピーと削除
Path source = Paths.get("data.txt");
Path target = Paths.get("backup.txt");
// コピー(上書きあり)
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
// 削除
Files.deleteIfExists(source);
注意点・よくあるミス
注意点 |
内容 |
例外処理が必須 |
多くのメソッドで IOException を投げる |
createFile() は既存ファイルがあると例外 |
上書きしたい場合は write() を使う |
readAllLines() は大きなファイルに不向き |
→ lines() を使用すると効率的 |
walk() は再帰探索向け |
ファイル一覧を取得するのに便利 |
まとめ:Files / Path / File の役割
クラス |
役割 |
Path |
パス情報(名前や構造) |
Files |
実体操作(読み書き・作成・削除など) |
File |
旧API。基本的には Path と Files の使用が推奨される |