LoginSignup
0
1

More than 3 years have passed since last update.

【Java】ファイルシステム操作

Posted at

ファイルシステム操作

  • Filesクラス
    • getPathメソッドでPathオブジェクトを生成
    • FileSystems.getDefaultメソッドで現在のファイルシステム取得
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class Main {
  public static void main(String[] args) {
    try {
      //現在のファイルシステム取得
      var fs = FileSystems.getDefault();
      var path1 = fs.getPath("./sample.txt");
      //ファイル存在確認
      System.out.println(Files.exists(path1));       //true
      //ファイル読み取り可能か
      System.out.println(Files.isReadable(path1));   //true
      //ファイル書き込み可能か
      System.out.println(Files.isWritable(path1));   //true
      //ファイル実行可能か
      System.out.println(Files.isExecutable(path1)); //true
      //ファイルサイズ
      System.out.println(Files.size(path1));
      //ファイルコピー
      var path2 = Files.copy(path1, fs.getPath("./copy.txt"),
        StandardCopyOption.REPLACE_EXISTING);
      //ファイル移動
      Files.move(path2, fs.getPath("./sub/copy.txt"),
        StandardCopyOption.REPLACE_EXISTING);
     //ファイル名変更
      var path3 = Files.move(path1, fs.getPath("./sub/rename.txt"),
        StandardCopyOption.REPLACE_EXISTING);
      //ファイル削除
      Files.delete(path3);
      //ファイル存在する場合削除(例外発生なし)
      Files.deleteIfExists(path3);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

フォルダ操作

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class Main {
  public static void main(String[] args) {
    try {
      var fs = FileSystems.getDefault();
      var dir1 = fs.getPath("./playground");
      var dir2 = fs.getPath("./data");
      //フォルダ作成
      Files.createDirectories(dir1);
      //フォルダ存在?
      System.out.println(Files.exists(dir1)); //true
      //フォルダか?
      System.out.println(Files.isDirectory(dir1)); //true
      //dir2配下のサブファイル/フォルダstream取得
      var s = Files.list(dir2);
      //.logで終わるファイル名取得
      s.filter(v -> v.getFileName().toString().endsWith(".log")).
        forEach(System.out::println); //./data/test.log
      //フォルダコピー
      var dir3 = Files.copy(dir1, fs.getPath("./data"),
        StandardCopyOption.REPLACE_EXISTING);
      //フォルダ移動
      Files.move(dir3, fs.getPath("./data"),
          StandardCopyOption.REPLACE_EXISTING);
      //フォルダ削除
      Files.delete(fs.getPath("./data/sub"));
      //フォルダ存在するときのみ削除
      Files.deleteIfExists(fs.getPath("./data/sub"));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
0
1
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
1