広告

Java : AccessDeniedException - API使用例

AccessDeniedException (Java SE 23 & JDK 23) の使い方まとめです。
ほとんどのメソッドにサンプルコードがあります。
APIドキュメントのおともにどうぞ。


概要

通常はファイル・アクセス権またはその他のアクセス・チェックのために、ファイル・システム操作が拒否されたときにスローされるチェック例外です。

クラス構成

AccessDeniedException はチェック例外です。
ファイルシステムに対してアクセスが拒否されたときに発生します。

final var dir = Path.of("R:", "java-work", "dir");
System.out.println(dir); // R:\java-work\dir

Files.createDirectory(dir);
System.out.println(Files.isDirectory(dir)); // true

try {
    Files.writeString(dir, "abc");
} catch (AccessDeniedException e) {
    System.out.println("AccessDeniedException!");
}

// 結果
// ↓
//AccessDeniedException!

コンストラクタ

AccessDeniedException (String file)

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

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

AccessDeniedException (String file, String other, String reason)

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

final var e = new AccessDeniedException("aaa.txt", "bbb.txt", "Reason!");
System.out.println(e); // java.nio.file.AccessDeniedException: 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!

FileSystemExceptionで宣言されたメソッド

getFile, getMessage, getOtherFile, getReason

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

Throwableで宣言されたメソッド

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

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


関連記事

ページの先頭へ