我有以下代码,我需要捕获AccessDeniedException异常
@H_403_2@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");
}
}
}
如果sample.txt是只读的,我输出为“找不到文件”而不是“访问已拒绝”.我想了解这是什么原因?另外,上述捕获AccessDeniedException的结构是否正确?
解决方法
AccessDeniedException
仅由新文件API抛出;旧的文件API(与此PrintWriter构造函数一起使用)只知道如何抛出FileNotFoundException,即使真正的文件系统级问题不是“文件不存在”.
您必须使用新API打开目标文件的输出流;那么你可以有有意义的例外:
@H_403_2@// _will_ throw AccessDeniedException on access problems final OutputStream out = Files.newOutputStream(Paths.get(filename)); final PrintWriter writer = new PrintWriter(out);更一般地,新文件API定义了FileSystemException
(继承IOException),由新API定义的所有新的有意义的异常都继承.
这意味着您可以在catch子句中明确区分由文件系统级错误和“真正的”I / O错误引起的错误,这些错误是旧API无法做到的:
@H_403_2@try { // some new file API operation } catch (FileSystemException e) { // deal with fs error } catch (IOException e) { // deal with I/O error }