我需要检查给定的二进制文件是否具有写入权限。文件类 API 有一个错误,它已在 JDK7 中修复,但我不能只升级到它。
这是错误的链接:http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6203387
当我打开 FileOutputStream 时,它损坏了二进制文件,Explorer 显示它们的大小为零并且无法启动它。这是代码片段。
操作系统:Win7
请帮助我理解为什么仅打开输出流(不写入任何内容)会损坏二进制文件。是否有解决此问题的方法?
这是代码片段:
private boolean hasWriteAccess(File file) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
} catch (Exception e) {
e.printStackTrace();
if(fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return false;
}
return true;
}
最佳答案
When I open a FileOutputStream it corrupts the binary files and Explorer shows their size as zero
它不会损坏文件 - 它会截断它。
如果您想以“附加”模式打开它,请使用允许这样做的构造函数重载:
fos = new FileOutputStream(file, true);
查看您的代码,这几乎肯定是您想要做的。
正如安德鲁所说,您也应该始终关闭流。
关于java - 为什么将 FileOutputStream 打开到二进制文件会损坏它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13085439/