Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中的AccessDeniedException异常_Java_File_Exception_Exception Handling - Fatal编程技术网

java中的AccessDeniedException异常

java中的AccessDeniedException异常,java,file,exception,exception-handling,Java,File,Exception,Exception Handling,我有以下代码需要捕获AccessDeniedExceptionexception import java.io.PrintWriter; import java.io.IOException; import java.nio.file.AccessDeniedException; class MyFileClass { public void write() throws IOException { PrintWriter out = new PrintWriter("

我有以下代码需要捕获
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");
    }
  }
}

在sample.txt为只读的情况下,我得到的输出是“未找到文件”,而不是“访问拒绝””。我想知道这是什么原因?此外,用于捕获
AccessDeniedException
的上述结构是否正确?

PrintWriter
中没有此类
AccessDeniedException

SecurityException
是由
PrintWriter

如果存在安全管理器并且checkWrite(file.getPath())被拒绝 对文件的写访问权限

仅由新文件API引发;旧的文件API(与此
PrintWriter
构造函数一起使用)只知道如何抛出
FileNotFoundException
,即使真正的文件系统级问题不是“文件不存在”

您必须使用新的API打开目标文件的输出流;然后您可以有有意义的异常:

// _will_ throw AccessDeniedException on access problems
final OutputStream out = Files.newOutputStream(Paths.get(filename));
final PrintWriter writer = new PrintWriter(out);
更一般地说,新文件API定义(继承
IOException
),新API定义的所有新的、有意义的异常都将继承

这意味着您可以在catch子句中清楚地区分由文件系统级错误和“真实”I/O错误引起的内容,这是旧API无法做到的:

try {
    // some new file API operation
} catch (FileSystemException e) {
    // deal with fs error
} catch (IOException e) {
    // deal with I/O error
}

不要打印,使用e.printStackTrace()在控制台中获取详细的错误消息print complete exception stack trace并粘贴它当文件未设置为只读时,程序是否找到该文件?这对我有帮助:抱歉,但不幸的是,这是错误的;旧文件API已损坏,如果您没有任何访问权限,将抛出
FileNotFoundException
。@fge请提供一些文档。我不知道。这对我也有帮助。呃,不幸的是,这从来没有被正确记录过。除了Java 6中不存在
AccessDeniedException
这一事实,并且出于兼容性原因,他们无法更改异常thrown@fge不是那么简单。你们都对了一半。如果您在安全管理器下运行,并且您的.policy文件不允许访问该文件,则会引发SecurityException。如果操作系统不允许访问该文件,将引发FileNotFoundException。@AJ-接受您的回答,现在我知道PrintWriter不会引发AccessDeniedException。但是,当客户端试图写入指定路径上存在但具有只读访问权限的文件时,将捕获FileNotFoundException