概要
java.nio.file.Files
クラスは、ファイルの作成・コピー・削除・移動・属性の読み書きなど、さまざまなファイル操作を簡単に行うためのメソッドを提供する。
主なメソッド
-
copy(Path source, Path target, CopyOption... options)
:
指定したファイルを別の場所にコピーする。
コピー元のファイルは残る。 -
createFile(Path path)
:
指定したファイルを新規作成する。 -
delete(Path path)
:
指定したファイルを削除する。 -
move(Path source, Path target, CopyOption... options)
:
指定したファイルを別の場所に移動する。
コピー元のファイルは消える。 -
exists(Path path)
:
指定したパスにファイルが存在するかどうかを確認する。 -
deleteIfExists(Path path)
:
指定したパスのファイルの存在確認と削除を同時に行う。 -
getAttribute(Path path, String attribute, LinkOption... options)
やsetAttribute(Path path, String attribute, Object value, LinkOption... options)
:
ファイルの属性の読み取り、設定をする。 -
getLastModifiedTime(Path path)
:
ファイルの最終更新日を調べる。 -
getPosixFilePermission(Path path)
:
ファイルのアクセス権を調べる。 -
createDirectory(Path dir, FileAttribute<?>... attrs)
:
指定したディレクトリを作成する。 -
newBufferedReader(Path path)
:
指定されたファイルを読み取るためのBufferedReader
を生成する。 -
newBufferedWriter(Path path)
:
指定されたファイルを書き込むためのBufferedReader
を生成する。
書き込みのオプションであるStandardOpenOption
を追加することができる。 -
list(Path dir)
:
指定されたディレクトリやサブディレクトリの一覧を取得する。 -
walk(Path start, int maxDepth, FileVisitOption... options) throws IOException
:
指定されたディレクトリやサブディレクトリの一覧を再帰的に取得する。 -
find(Path start,int maxDepth,BiPredicate<Path, BasicFileAttributes> matcher,FileVisitOption... options) throws IOException
:
指定されたディレクトリやサブディレクトリの一覧を条件付きで取得する。
※ list()
、walk()
、find()
の比較はこちら
-
Path walkFileTree(Path start,Set<FileVisitOption>,int maxDepth,FileVisitor<? super Path> visitor)throws IOException
:
指定されたディレクトリから再帰的に全てのファイルやサブディレクトリを走査する。
例
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class FilesExample {
public static void main(String[] args) {
// ファイルの作成
Path filePath = Paths.get("example.txt");
String content = "Hello, World!";
try {
Files.write(filePath, content.getBytes());
System.out.println("ファイルが作成されました。");
} catch (IOException e) {
e.printStackTrace();
}
// ファイルのコピー
Path targetPath = Paths.get("example_copy.txt");
try {
Files.copy(filePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("ファイルがコピーされました。");
} catch (IOException e) {
e.printStackTrace();
}
// ファイルの削除
try {
Files.delete(filePath);
System.out.println("ファイルが削除されました。");
} catch (IOException e) {
e.printStackTrace();
}
// ファイルの移動
Path sourcePath = Paths.get("example_copy.txt");
Path destinationPath = Paths.get("moved_file.txt");
try {
Files.move(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("ファイルが移動されました。");
} catch (IOException e) {
e.printStackTrace();
}
}
}
上記の例では、以下の流れで処理をしている。
-
Files.write()
メソッドを使用してexample.txt
という名前のファイルを作成し、内容を"Hello, World!"として書き込む。 -
Files.copy()
メソッドを使用してexample.txt
をexample_copy.txt
にコピーする。 -
Files.delete()
メソッドを使用してexample.txt
を削除する。 -
Files.move()
メソッドを使用してexample_copy.txt
をmoved_file.txt
に移動させる。
実行結果
ファイルが作成されました。
ファイルがコピーされました。
ファイルが削除されました。
ファイルが移動されました。