我的目标
我试图将简单对象(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
[…]
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 reasonSecurityException
– if a security manager exists and its checkWrite
method denies write access to the file.
>我确定我对该目录具有读/写权限;没有名为test.txt的现有文件,因此它不能被另一个程序锁定.
>将fileName更改为绝对路径,我确定我可以写入没有任何区别.
解决方法:
如果文件处于只读模式,则可以重现.你可以这样尝试吗
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磁盘上写入.