我的目标

我试图将简单对象(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.(FileOutputStream.java:213)

at java.io.FileOutputStream.(FileOutputStream.java:101)

at Test.main(Test.java:33)

我试图修复它

>根据文档,如果文件尚不存在,我希望可以创建该文件.我已经彻底阅读了我尝试使用的方法的Javadoc,在此引用其摘录(重点是我的):

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.

>我确定我对该目录具有读/写权限;没有名为test.txt的现有文件,因此它不能被另一个程序锁定.

>将fileName更改为绝对路径,我确定我可以写入没有任何区别.

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐