我尝试读取该文件并得到 FileNotFoundExeption。
File file = new File("News.out");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
try{
in.readObject();
}
我检查该文件是否确实存在于目录中并检查该文件的“可读”属性。
然后我添加了“可读”和“可写”属性的编程设置
file.setReadable(true);
file.setWritable(true);
System.out.println(file.canRead());
System.out.println(file.canWrite());
并在日志中得到错误,错误。
这可能是什么原因?
编辑:
我尝试了 JSR 203 并使用以下代码:
Path path = FileSystems.getDefault().getPath(filename);
try(
final InputStream in = Files.newInputStream(path);
) {
ObjectInputStream objectInputStream = new ObjectInputStream(in);
newsStorage.setEntities((ArrayList<News>) objectInputStream.readObject());
} catch (NoSuchFileException e) {
createFile(path, filename);
handleException(e);
}
和createFile()方法:
private void createFile(Path path, String string) {
try {
Files.newOutputStream(path, StandardOpenOption.CREATE);
} catch (IOException e1) {
e1.printStackTrace();
}
}
文件未创建。
我的理解正确吗
Files.newOutputStream(path, StandardOpenOption.CREATE);
应该创建一个文件吗?
最佳答案
帮自己一个忙,删除文件
。请改用 JSR 203。
尝试并使用:
try (
final InputStream in = Files.newInputStream("News.out");
) {
// work with "in" here
}
如果您无法执行打开操作,那么至少会出现一个异常,告诉您到底出了什么问题,这是 File
从来无法做到的事情。
之后,如果您想设置文件的权限,也可以使用 JSR 203 来执行此操作,但这取决于底层文件系统的功能。如果您的文件系统兼容 POSIX,那么您可以使用 this method例如。但也可能您无法修改文件的权限。
关于java - file.setReadable(true) 之后文件不可读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44215357/