java.nio.file.Filesについて

java.nio.file.Filesクラスは、Javaプログラムでファイルやディレクトリを操作するための便利なメソッドです。
以下に、Filesクラスの一部のメソッドとその使い方を説明します。

deleteIfExists()

Path filePath = Path.of("path/to/file.txt");
boolean deleted = Files.deleteIfExists(filePath);
if (deleted) {
    System.out.println("File deleted successfully.");
} else {
    System.out.println("File does not exist.");
}

exists()

Path path = Path.of("path/to/file.txt");
boolean exists = Files.exists(path);

write()

Path path = Path.of("path/to/file.txt");
String content = "Hello, world!";
Files.write(path, content.getBytes());

copy()

Path sourcePath = Path.of("path/to/source.txt");
Path targetPath = Path.of("path/to/target.txt");
Files.copy(sourcePath, targetPath);

delete()

Path path = Path.of("path/to/file.txt");
Files.delete(path);

createDirectory()

Path path = Path.of("path/to/new/directory");
Files.createDirectory(path);

下記に続きの使い方を示します。

参考文献

https://docs.oracle.com/javase/jp/8/docs/api/java/nio/file/Files.html

コメントを残す

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