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