繁体   English   中英

尝试写入新文件时,FileNotFoundException(拒绝访问)

[英]FileNotFoundException (Access is denied) when trying to write to a new file

我的目标

我试图将简单对象( SimpleType )写入文件,以便稍后加载文件并重新创建对象。

我的设定

我目前正在使用Windows 7计算机上的NetBeans IDE(JDK8)。 不过,我认为这不应该有所作为。

这是我想写入文件的类型:

public class SimpleType implements Serializable {
    boolean[] a;
    boolean[] b;
}

这是我试图运行的代码:

public class Test {
    public static void main(String[] args)
        throws IOException, ClassNotFoundException {
        String fileName = "test.txt";
        SimpleType foo = new SimpleType;
        try (ObjectOutputStream out = new ObjectOutputStream(new
             BufferedOutputStream(new FileOutputStream(fileName)))) {
            out.writeObject(foo);
            out.close();
        }
    }
}

我的问题

代码编译并运行,但始终抛出FileNotFoundException

Exception in thread "main" java.io.FileNotFoundException: test.txt (Access is denied)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
    at Test.main(Test.java:33)

我尝试修复它

  • 根据文档,如果文件不存在,我希望创建该文件。 我已经彻底阅读了我试图使用的方法的Javadoc,这是我在这里引用的一段摘录(强调我的):

public FileOutputStream(String name) throws FileNotFoundException

[...]

参数:
name - 依赖于系统的文件名
抛出:
FileNotFoundException - 如果文件存在但是是目录而不是常规文件, 则不存在但无法创建 ,或者由于任何其他原因无法打开SecurityException - 如果存在安全管理器且其checkWrite方法拒绝对文件的写访问。

  • 我确信我在目录中有读/写权限; 没有名为test.txt的现有文件,因此无法被其他程序锁定。

  • fileName更改为绝对路径我相信我可以写入没有任何区别。

如果文件处于只读模式,则可以重现。 你能尝试这样吗?

public static void main(String[] args) {
      String fileName = "sampleObjectFile.txt";
      SampleObject sampleObject = new SampleObject();
      File file = new File(fileName);
      file.setWritable(true); //make it writable.
      try(ObjectOutputStream outputStream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)))){
           outputStream.writeObject(sampleObject);
           outputStream.close();
      } catch (IOException e) {
           e.printStackTrace();
      }
 }

如果您在OS磁盘上写入文件,则需要管理员权限。 所以避免在OS磁盘上写。

通常这是因为您尝试在文件系统不允许的位置写入(例如,在Windows7中,您无法在c :)中编写新文件。 尝试使用Microsoft的SysInternals中的 procmon来调查程序尝试编写的位置。 添加一个新的过滤器(路径包含test.txt),看看会发生什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM