Recipe 11.6 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 Recipe 11.1, many methods report on a file. By contrast, only a few 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 corresponding method setReadWrite( ). 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 it 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 Recipe 11.1), or you can get the value for a given date by calling the Date class's getTime( ) method (see Recipe 6.1). 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.



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net