尝试写入新文件时出现“FileNotFoundException(访问被拒绝)”错误

3

我的目标

我想要将简单对象(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更改为我确定可以写入的绝对路径并没有任何区别。


文件在哪里?请发布确切的路径。 - marc3l
我在Ubuntu上运行了上述代码,没有出现任何异常。 - Niels Billen
2个回答

3
如果文件处于只读模式,问题可以复现。您可以尝试像这样操作。
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 磁盘上进行写入操作。


1
通常这是因为您正在尝试在FileSystem不允许的位置写入(例如在Windows7中,您不能在c:中写入新文件)。 尝试使用Microsoft的SysInternalsprocmon调查程序正在尝试写入的位置。 添加一个新的过滤器(路径包含test.txt)并查看发生了什么。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接