1

I need to check whether given binary file has write access or not. File class API has a bug and its fixed in JDK7 but I can not just upgrade to it.

Here is the link to the bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6203387

When I open a FileOutputStream it corrupts the binary files and Explorer shows their size as zero and can not launch it. Here is the code snippet.

OS: Win7

Please help me to understand why just opening an output stream (not writing anything) corrupts a binary file. Is there any work around for this problem?

Here is the code snippet:

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;
}
4

2 回答 2

6

When I open a FileOutputStream it corrupts the binary files and Explorer shows their size as zero

It doesn't corrupt the file - it truncates it.

If you want to open it in "append" mode, use the constructor overload which allows that:

fos = new FileOutputStream(file, true);

Looking at your code, that's almost certainly what you want to do.

As Andrew says, you should always close the stream too.

于 2012-10-26T10:53:11.607 回答
1

When you use

new FileOutputStream(file);

it will always truncate the file.

If you want to open the file without truncating it you can use append instead.

new FileOutputStream(file, true).close();
于 2012-10-26T10:54:11.040 回答