0
0

More than 1 year has passed since last update.

【JavaGold】NIO.2②

Last updated at Posted at 2023-07-24

概要

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();
        }
    }
}

上記の例では、以下の流れで処理をしている。

  1. Files.write()メソッドを使用してexample.txtという名前のファイルを作成し、内容を"Hello, World!"として書き込む。
  2. Files.copy()メソッドを使用してexample.txtexample_copy.txtにコピーする。
  3. Files.delete()メソッドを使用してexample.txtを削除する。
  4. Files.move()メソッドを使用してexample_copy.txtmoved_file.txtに移動させる。
実行結果
ファイルが作成されました。
ファイルがコピーされました。
ファイルが削除されました。
ファイルが移動されました。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0