広告

Java : NoSuchFileException - API使用例

NoSuchFileException (Java SE 21 & JDK 21) の使用例まとめです。
だいたいのメソッドを網羅済みです。
API仕様書のおともにどうぞ。


概要

存在しないファイルへのアクセスを試みた場合にスローされるチェック例外です。

クラス構成

NoSuchFileException は、操作する対象のファイルが存在しないときに投げれられる例外です。

例えば、

  • 削除しようとしたファイルが存在しない
  • コピーしようとしたファイルが存在しない

などです。

final var file = Path.of("R:", "java-work", "aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt
System.out.println(Files.notExists(file)); // true

try {
    System.out.println("-- delete --");
    Files.delete(file);
} catch (NoSuchFileException e) {
    System.out.println(e);
}

// 結果
// ↓
//-- delete --
//java.nio.file.NoSuchFileException: R:\java-work\aaa.txt
final var src = Path.of("R:", "java-work", "aaa.txt");
final var dst = Path.of("R:", "java-work", "bbb.txt");

System.out.println(src); // R:\java-work\aaa.txt
System.out.println(dst); // R:\java-work\bbb.txt
System.out.println(Files.notExists(src)); // true
System.out.println(Files.notExists(dst)); // true

try {
    System.out.println("-- copy --");
    Files.copy(src, dst);
} catch (NoSuchFileException e) {
    System.out.println(e);
}

// 結果
// ↓
//-- copy --
//java.nio.file.NoSuchFileException: R:\java-work\aaa.txt

コンストラクタ

NoSuchFileException (String file)

このクラスのインスタンスを構築します。

final var e = new NoSuchFileException("aaa.txt");
System.out.println(e); // java.nio.file.NoSuchFileException: aaa.txt
System.out.println(e.getFile()); // aaa.txt

NoSuchFileException (String file, String other, String reason)

このクラスのインスタンスを構築します。

final var e = new NoSuchFileException("aaa.txt", "bbb.txt", "Reason!");
System.out.println(e); // java.nio.file.NoSuchFileException: aaa.txt -> bbb.txt: Reason!
System.out.println(e.getFile()); // aaa.txt
System.out.println(e.getOtherFile()); // bbb.txt
System.out.println(e.getReason()); // Reason!
System.out.println(e.getMessage()); // aaa.txt -> bbb.txt: Reason!

FileSystemExceptionで宣言されたメソッド

getFile, getMessage, getOtherFile, getReason

Java API 使用例 : FileSystemException」をご参照ください。

Throwableで宣言されたメソッド

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Java API 使用例 : Throwable」をご参照ください。


関連記事

ページの先頭へ