尝试写入新文件时出现 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)

我尝试修复它

public FileOutputStream(String name) throws FileNotFoundException

[...]

Parameters:
name - the system-dependent filename
Throws:
FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason SecurityException - if a security manager exists and its checkWrite method denies write access to the file.

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

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

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 磁盘。