Changing File Attributes

Problem

You want to change attributes of a file other than its name.

Solution

Use setReadOnly( ) or setLastModified( ).

Discussion

As we saw in Section 10.2, there are many methods that report on a file. By contrast, there are only a few that change the file.

setReadOnly( ) turns on read-only for a given file or directory. It returns true if it succeeds, otherwise false. There is no setReadWrite( ) (at least as of JDK 1.3; I don’t know why this method was overlooked). Since you can’t undo a setReadOnly( ), use this method with care!

setLastModified( ) allows you to play games with the modification time of a file. This is normally not a good game to play, but is useful in some types of backup/restore programs. This method takes an argument that is the number of milliseconds (not seconds) since the beginning of time (January 1, 1970). You can get the original value for the file by calling getLastModified( ) (see Section 10.2) or you can get the value for a given date by calling the Date class’s getTime( ) method (see Section 6.2). setLastModified( ) returns true if it succeeded, and false otherwise.

The interesting thing is that the documentation claims that “File objects are immutable,” meaning that their state doesn’t change. But does calling setReadOnly( ) affect the return value of canRead( ) ? Let’s find out:

import java.io.*;

public class ReadOnly {
    public static void main(String[] a) throws IOException {

        File f = new File("f");

        if (!f.createNewFile(  )) {
            System.out.println("Can't create new file.");
            return;
        }

        if (!f.canWrite(  )) {
            System.out.println("Can't write new file!");
            return;
        }

        if (!f.setReadOnly(  )) {
            System.out.println("Grrr! Can't set file read-only.");
            return;
        }

        if (f.canWrite(  )) {
            System.out.println("Most immutable, captain!");
            System.out.println("But it still says canWrite(  ) after setReadOnly");
            return;
        } else {
            System.out.println("Logical, captain!");
            System.out.println 
                ("canWrite(  ) correctly returns false after setReadOnly");
        }
    }
}

When I run it, this program reports what I (and I hope you) would expect:

$ jr ReadOnly
+ jikes +E -d . ReadOnly.java
+ java ReadOnly
Logical, captain!
canWrite(  ) correctly returns false after setReadOnly
$

So, the immutability of a File object refers only to the pathname it contains, not to its read-only-ness.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.34.197