Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata