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;
}
Alexis Pigeon
  • 7,423
  • 11
  • 39
  • 44

2 Answers2

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
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();
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130