java.nio.file.Filesクラスの使い方1の続きです。
move()
- ファイルの移動・名前の変更:
Path sourcePath = Path.of("path/to/source.txt");
Path targetPath = Path.of("path/to/target.txt");
Files.move(sourcePath, targetPath);
getAttribute(), setAttribute()
- ファイルの属性の取得と変更: ファイルの属性(例: 最終更新日時、ファイルサイズなど)を取得、変更することができます。
Path path = Path.of("path/to/file.txt");
BasicFileAttributeView attributeView = Files.getFileAttributeView(path, BasicFileAttributeView.class);
BasicFileAttributes attributes = attributeView.readAttributes();
System.out.println("Last Modified: " + attributes.lastModifiedTime());
System.out.println("File Size: " + attributes.size());
// ファイルの最終更新日時を変更する例
attributeView.setTimes(null, null, null);
isSameFile()
- ファイルの比較:
Path path1 = Path.of("path/to/file1.txt");
Path path2 = Path.of("path/to/file2.txt");
boolean isSame = Files.isSameFile(path1, path2);
System.out.println("Same file: " + isSame);
createTempFile()
- ファイルの一時的な作成: 一時ファイルは、プログラム実行中に一時的に使用され、不要になったら削除されます。
Path tempFilePath = Files.createTempFile("prefix", ".txt");
System.out.println("Temp file path: " + tempFilePath);
//一時ファイルの使用
...
//一時ファイルの削除
Files.delete(tempFilePath);
zip(), unzip()
- ファイルの圧縮と解凍
Path sourcePath = Path.of("path/to/source");
Path zipFilePath = Path.of("path/to/archive.zip");
Files.zip(sourcePath, zipFilePath);
//ZIPファイルの解凍
Path targetPath = Path.of("path/to/target");
Files.unzip(zipFilePath, targetPath);
newBufferedReader(), newBufferedWriter()
- ファイルの読み書きロック取得: 複数のプロセスやスレッドから同時にファイルにアクセスすることを制御できます。
Path filePath = Path.of("path/to/file.txt");
// ファイルの読み込みロックを取得
try (var reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) {
// ファイルの読み込み処理
}
// ファイルの書き込みロックを取得
try (var writer = Files.newBufferedWriter(filePath, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
// ファイルの書き込み処理
}
参考文献
https://docs.oracle.com/javase/jp/8/docs/api/java/nio/file/Files.html