Java Reference
In-Depth Information
// Finally, move the config file to its new home
f
.
renameTo
(
new
File
(
configdir
,
".config"
));
}
This shows some of the flexibility possible with the
File
class, but also demon‐
strates some of the problems with the abstraction. It is very general, and this
requires a lot of methods to interrogate a
File
object in order to determine what it
actually represents and its capabilities.
Files
The
File
class has a very large number of methods on it, but some basic functional‐
ity (notably a way to read the contents of a file) is not, and never has been provided
directly.
Here's a quick summary of
File
methods:
// Permissions management
boolean
canX
=
f
.
canExecute
();
boolean
canR
=
f
.
canRead
();
boolean
canW
=
f
.
canWrite
();
boolean
ok
;
ok
=
f
.
setReadOnly
();
ok
=
f
.
setExecutable
(
true
);
ok
=
f
.
setReadable
(
true
);
ok
=
f
.
setWritable
(
false
);
// Different views of the file's name
File
absF
=
f
.
getAbsoluteFile
();
File
canF
=
f
.
getCanonicalFile
();
String
absName
=
f
.
getAbsolutePath
();
String
canName
=
f
.
getCanonicalPath
();
String
name
=
f
.
getName
();
String
pName
=
getParent
();
URI
fileURI
=
f
.
toURI
();
// Create URI for File path
// File metadata
boolean
exists
=
f
.
exists
();
boolean
isAbs
=
f
.
isAbsolute
();
boolean
isDir
=
f
.
isDirectory
();
boolean
isFile
=
f
.
isFile
();
boolean
isHidden
=
f
.
isHidden
();
long
modTime
=
f
.
lastModified
();
// milliseconds since epoch
boolean
updateOK
=
f
.
setLastModified
(
updateTime
);
// milliseconds
long
fileLen
=
f
.
length
();
// File management operations
boolean
renamed
=
f
.
renameTo
(
destFile
);
boolean
deleted
=
f
.
delete
();
// Create won't overwrite existing file