The intersection of technology and leadership

java.io.File setReadonly and canWrite broken on Windows

File.setReadonly(true) doesn’t actually work on windows (at least on the JDK that we’re working on). According to the bug report filed here, it is just setting the DOS flag that prevents it from being deleted just not being written to.

Meanwhile, assuming you have mounted a read only disk partition in windows to, say X:, new File(“X:/”).canWrite() returns true when it really should be returning false. I’m still trying to find the bug reported to sun for this, or will later update this entry to include it. It seems to persist when running against both jdk1.5.0_15 and jdk1.6.0_07.

4 Comments

  1. Jens Goldhammer

    Hello, thanks for that comment. Is there any solution for that?

  2. Peter Tseng

    Try something like this:

    public static boolean canWrite(String path) {
    File file = new File(path);
    if (!file.canWrite()) {
    return false;
    }
    /* Java lies on Windows */
    try {
    new FileOutputStream(file, true).close();
    } catch (IOException e) {
    LOGGER.info(path + ” is not writable: ” + e.getLocalizedMessage());
    return false;
    }
    return true;
    }

  3. Patrick

    Cool. Thanks. I’ll give it a go!

  4. Peter Tseng

    No problem. You should be aware that this method may have performance issues if used in a loop or something, since you’re basically opening and closing the file.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2024 patkua@work

Theme by Anders NorenUp ↑