O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required