【问题标题】:FileNotFoundException (Access is denied) when trying to write to a new file尝试写入新文件时出现 FileNotFoundException(访问被拒绝)
【发布时间】:2015-03-06 12:57:03
【问题描述】:

我的目标

我正在尝试将简单对象 (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 更改为我确信我可以写入的绝对路径没有任何区别。

【问题讨论】:

  • 文件在哪里?请发布确切的路径。
  • 我运行了上面的代码,它在 Ubuntu 上毫无例外地为我工作。

标签: java io objectoutputstream


【解决方案1】:

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

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 磁盘上写入文件,则需要管理员权限。所以避免在操作系统磁盘上写入。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-05-19
      • 1970-01-01
      • 2015-11-05
      • 2019-06-21
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      相关资源
      最近更新 更多