Java Reference
In-Depth Information
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
Getting File Information
, 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. This method returns
true
if
it succeeds, otherwise
false
.
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 be-
ginning of Unix time (January 1, 1970). You can get the original value for the file by calling
getLastModified()
(see
Getting File Information
), or you can get the value for a given date
Among Dates/Times, YMDHMS, and Epoch Seconds
)
and multiplying by 1,000 to convert
seconds to mSec.
setLastModified()
returns
true
if it succeeded and
false
otherwise.
The interesting thing is that the documentation reads, in part, that “Instances of the
File
class are immutable,” which normally means that an object's fields don't change after the ob-
ject is constructed. But does calling
setReadOnly()
affect the return value of
canRead()
?
Let's find out:
public
public class
class
ReadOnly
ReadOnly
{
public
public static
static
void
void
main
(
String
[]
a
)
throws
throws
IOException
{
File f
=
new
new
File
(
"f"
);
iif
(!
f
.
createNewFile
()) {
System
.
out
.
println
(
"Can't create new file."
);