I have the following code where I need to catch AccessDeniedException
exception
import java.io.PrintWriter;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
class MyFileClass {
public void write()
throws IOException
{
PrintWriter out = new PrintWriter("sample.txt");
out.printf("%8.2f\n", 3.4);
out.close();
}
}
public class MyClass {
public static void main(String[] args)
throws Exception
{
try {
MyFileClass mf = new MyFileClass();
mf.write();
} catch (AccessDeniedException e) {
print("Access denided");
}
catch (FileNotFoundException e) {
print("File not found");
}
}
}
In case sample.txt is read only, I get output as "file not found" rather "Access denided". I would like to understand what is the reason for this? Also, is the above structure for catching AccessDeniedException
correct?
AccessDeniedException
is only thrown by the new file API; the old file API (which you use with this PrintWriter
constructor) only knows how to throw FileNotFoundException
even if the real filesystem-level problem is not "the file does not exist".
You have to use the new API to open an output stream to the destination file; then you can have meaningful exceptions:
// _will_ throw AccessDeniedException on access problems
final OutputStream out = Files.newOutputStream(Paths.get(filename));
final PrintWriter writer = new PrintWriter(out);
More generally, the new file API defines FileSystemException
(inheriting IOException
), which all new, meaningful exceptions defined by the new API inherit.
This means among other things that you can clearly separate, in catch clauses, what is caused by filesystem-level errors and "real" I/O errors, which you can't do with the old API:
try {
// some new file API operation
} catch (FileSystemException e) {
// deal with fs error
} catch (IOException e) {
// deal with I/O error
}
There is NO such AccessDeniedException
in PrintWriter
.
SecurityException
is the exception thrown by PrintWriter
If a security manager is present and checkWrite(file.getPath()) denies write access to the file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With