Without even opening the file, File lets you
find out about a file or directory, and lets you rename or delete it.
Because java.io.File can represent a file, wildcard,
or directory node, this class has many more uses than its name would suggest. File
is a misnomer, because File does not represent a file
at all, but rather the name of a file that may or may not actually exist.
File myFile = new File( "C:\\temp\\abc.txt" );
File myDir = new File( "/home/fundir" );
gets you access to a file. You feed it a filename or directory name suitable for
the native platform, not a URL. On windows, you can use /
and \ interchangeably. \ has to be doubled because it is also the Java escape
character.
Methods For Manipulating Filenames and Files
-
File.exists
: does a file or directory of this name exist?. Beware of code like this:
String f = null;
if ( new File(f+ ".ext" ) .exists() )
will return true, because null.ext is considered to
exist as the null device. In a similar way com1.txt is
considered to exist as the COM1: port even when there is no such file. Avoid
filenames of the form com?.* and lpt?.*.
-
File.delete
: erase, remove, kill, destroy, unlink, and nuke a file. The File
object is completely unaffected by deleting the file on disk, whether you do it
with File.delete() or by any independent means. See
also deleteOnExit. Can also be used to delete empty
directories.
-
File.renameTo
: renaming (or moving) a file. Note, it does not change the name inside the File
object, just the name of the corresponding file on disk. You can't use the File
object to access the renamed file. You need a fresh one with the new name.
-
File.length
how many bytes are in this file.
-
File.list
String[] fileNames = file.list();
get list of files in this directory. Wildcards won't work. Note it returns an
array of Strings, not including the directory, not File
objects. Files are not in any particular order. They include the subdirectories,
but not the . or .. entries.
Often used with a FilenameFilter to select some of
the files.
String[] fileNames = file.list( someFilter );
Your FilenameFilter needs at a minimum to filter
with File.isDirectory().
-
RandomAccessFile.setLength
chop/grow this file to n bytes long. JDK 1.2+ only.
-
File.canRead
does this file exist and do you have permission to read it?
-
File.canWrite
does this file exist and do you have permission to write it? Returns false if
the file does not exist, even though you probably could write such a file. Note
that if it does not exist, you can write it, but canWrite will return false.
setReadOnly lets you make a file read-only, but
there is no way to undo the read-only status, other than my copying it or using exec.
-
File.lastModified
get last modified timestamp. setLastModified lets
you change the lastModified date
File f = new File( "abc.txt" );
long timestamp = f.lastModified();
Date when = new Date(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat( "EEEE yyyy/MM/dd hh:mm:ss aa zz : zzzzzz" );
sdf.setTimeZone(TimeZone.getDefault());
String display = sdf.format(when);
If you don't have proper access permission, you will get -1 results. With Java
1.4 you can now set the date as well with File.setLastModified(
long timestamp ).
-
File.setlastModified
set last modified timestamp. You cannot read or access the last access date or
the create date without using jni or exec.
-
File.setReadOnly
Lets you make a file read-only, but does not let you make in writable.
-
taking apart a filename:
There are strange filenames like C:\ . .. ../sub C:.
Make sure you test that your code works with them as well.
-
File.isDirectory
is there a directory by this name?
-
File.mkdirs
(not mkDirs), make a directory and any necessary parent directories. mkdir
is similar, but does not create parent directories.
-
File.listRoots
a list of available drives, JDK 1.2 only.
-
javax.swing.filechooser.FileSystemView.getFileSystemView().getRoots()
alternate way to get a list of available drives.
-
File.isFile
is there a file by this name?
-
File.getName
just the name and extension.
-
File.getPath
partially qualified directory + name + extension.
-
File.toString
partially qualified directory + name + extension.
-
File.getAbsolutePath
fully qualified directory + name + extension. It won't give you the precise case
of the file! It will echo back to you the case you used.
-
File.getParent
drive + fully qualified directory.
Uses \ instead of / for the separator in Win95/NT. Only works gives you the
absute parent if you provide fully qualified filneames. If you feed it an
unqualified one, you will just get a null result. It also produces gibberish for
absolute filenames.
-
File.getCanonicalPath
drive + fully qualified directory + name + extension.
Uses \ instead of / for the separator in Win95/NT. Gets you the precise case.
May throw an IOException. To avoid that use the
cruder getAbsolutePath.
-
File.getCanonicalFile
drive + fully qualified directory + name + extension packaged up in a new File
object.
Uses \ instead of / for the separator in Win95/NT. Gets you the precise case.
-
File(dir, name)
constructor builds file name out of two pieces. The first directory parameter
may optionally a String or a File
object. The second filename parameter must be a String.
This is not nearly as clever as you might imagine. All does is glue the two
pieces together with a / between. So you can't do things like this:
new File ( ".", "C:/fileInRoot.txt" )
if you try:
new File ( "myDir" , "/otherDir" )
you will get the same effect as:
File("myDir/OtherDir" )
not
File( "/OtherDir" );
In other words, the file parameter has to be truly relative to the directory
parameter. However, embedded /s like this will work:
new File ( "species" , "clan/individual.txt" )
and has the same effect as:
new File ( "species/clan/individual.txt" );
One tool to help sort this all out is File.isAbsolute();
Hints
-
There are no tools to test or change file attributes such as hidden,
system or archive, except for setReadOnly and setLastModified.
The java.io.FilePermission class can't be used for
changing permissions of operating system files. It is used for specifying the
permissions of files within a Java program. Java does not support the hidden
attribute because not all platforms have it. Unix and Linux use a convention of
hiding files whose names begin with a ..
-
new File does not actually create a file. The file
does not get created until you open some sort of stream or reader. You can
create one explicitly with File.createNewFile().
-
Java does not let you change the current directory,
though you can discover it with new File(".").getCanonicalPath().
The concept of current does not really make sense in a multithreaded environment.
You can keep track of your own simulated current directory string (possibly on a
per thread or per Object basis), and use new File(dir,
filename) to construct a fully qualified filename. The constructor is not
very bright. It basically just glues the filename onto the end of the dir name
with a file separator. It does not cleverly merge the directory name and the
filename the way a command processor would merge the current directory name and
a partly qualified filename to get a fully qualified name. You can't, for
example, provide the constructor with a fully qualified filename as the file and
have it completely override the dir. The best way to understand its limitations
is to experiment and dump your results with File.getCanonicalPath.
Writing a smart merge would have to consider the naming conventions of each
platform. Another option is to write your own JNI CD native method that uses the
C chdir or _chdir function and GetStringUTFChars.
You could also use exec to spawn a cd command.
-
There are no tools to look for an extension. You have
to do that yourself with code like this:
String extension = "";
int whereDot = theFilename.lastIndexOf( '.' );
if ( 0 < whereDot && whereDot <= theFilename .length()-2 )
{
extension = theFilename .substring(whereDot+1 );
}
Make sure you do that on the filename proper, not the entire name, otherwise you
could be fooled by a dot the name of one of the directory nodes.
-
File also handles directories. You can use it to
delete, rename and test directories. File.list will
give you a list of files in this directory as an array of Strings. However, File
cannot handle wildcards. You have to use FilenameFilter.
-
File is not final. You
can extend it with your own features, e.g. methods to decompose the filename
into its composite pieces.
File and Record Locking
Java has no features for file or record locking. You
can kludge them by creating a dummy file whenever you are using the main file,
and deleting it when you are done. If all threads and processes using the file
do likewise, and sleep while the dummy semaphore file is present, waking
periodically to see if it has disappeared, you can arrange exclusive access.
Other than that, you would have to use JNI to hook into the OS's native file
locking scheme.
The easiest way to deal with this is to use an SQL
database manager which can deal with concurrent updates.
Platform Specific Filenames
Every platform uses a different filename format. Your Java apps will deal
directly with those filenames. You have only three tools to help you:
static String lineSeparator = System.getProperty ( "line.separator" );
File.separatorChar
File.pathSeparatorChar
You are safest to build up filenames programmatically like this:
/**
* Build a platform independent filename out of pieces
*
* @param drvLetter Drive letter or 0 (not '0') for none.
*
* @param path directories possibly containing embedded / or \
*
* @param fileName name of the file, possibly containing an embedded .
*/
String makeQualName(char drvLetter, String path, String fileName)
{
return(drvLetter == 0 ? "" : drvLetter + ":" )
+ File.separatorChar
+ path
+ File.separatorChar
+ fileName;
}
For WORA, it is best to use very conservative file naming conventions:
-
lower case only.
-
no punctuation.
-
no spaces.
-
no accented letters.
-
no control characters.
Anything else is bound to confuse some OS somewhere.
|
Win9x/NT |
Linux |
Apple iMac |
Groupe Bull GCOS 8
(JDK 1.1.6 beta) |
| lineSeparator |
"\r\n" |
"\n" |
"\r" |
"\n" |
| separatorChar |
'\\' |
'/' |
':' |
'/' |
| pathSeparatorChar |
';' |
':' |
N/A |
':' |
| absolute |
"C:\\myDir\\myFile.txt" |
"/usr/local/my.Dir/my.File.txt" |
"::myVolume:myDir:file.txt" |
"gcosuser/catalog/file.txt" |
| relative |
"myDir\\myFile.txt" |
"my.Dir/my.File.txt" |
"myDir:file.txt" |
"/catalog/file.txt"
(subordinate to the current GCOS 8 userid) |
| root |
"C:\\." |
"/." |
"::myVolume:" |
N/A |
| parent |
"..\\." |
"../." |
File.getParent() |
N/A |
| case sensitive |
no |
yes |
no |
no |
| charset |
A-Z a-z 0-9 accented - _ ~ ! @ # $ |
A-Z a-z 0-9 accented - _ ~ ! @ # $ |
Almost anything, Full Unicode, even control chars |
a-z 0-9 - _ . |
| avoid |
. : ; * @ % ^ & ( ) [ ] { } " ' < > ? + = / | |
: ; * @ % ^ & ( ) [ ] { } " ' < > ? + = / | |
: (. at beginning) ; * @ % ^ ( ) " ' < > ? + = / | |
: ; * @ % ^ & ( ) [ ] { } " ' < > ? + = / | ~ ! @ # $
accented |
| zip and jar files |
|
|
|
These files types are treated as a "container database" for a
collection of Java class files and other resources. The pathnames stored within
these files are not case sensitive and can be arbitrarily long.
GCOS 8 supports read-access to these files. |
| restrictions |
|
|
|
-
Each directory or file component must be less than or equal to 12 characters.
-
Both "." and ".." can be valid file names.
-
The construct "." does not refer to the current directory.
-
The construct ".." does not refer to the parent directory.
|
GCOS is a mainframe JVM implementation without GUI. It runs on mainframes that
use 36 bit words with non-IEEE floating point hardware. It has its roots in GE's
GECOS, was later taken over by Honeywell, and had been run by the French Company,
Groupe Bull since 1989. It is included mainly to show you just how different a
platform can be and still run Java apps unmodified.
Console I/O
The console i/o methods are in System, e.g.
| System.in.read(); |
read a byte |
| System.err.print() |
print a value |
| System.err.println(); |
print a value followed by a newline |
| System.out.print(); |
print a value |
| System.out.println(); |
print a value followed by a newline. |
| System.setIn(); |
redirect stdin to a file |
| System.setErr(); |
redirect stderr to a file |
| System.setOut(); |
redirect stdout to a file |
Applets
Unsigned Applets cannot read files on the local hard disk. The java.io.File
class won't let you read or write files on some other remote machine, e.g.
Applets can't read or write files on the server, even if they are signed.