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

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です