Files & Directories : Java Glossary
home F words local find no local find frame, full screen Google search web for topic jump to footer translate with Babelfish 2008-04-11 by Roedy Green ©1996-2008 Canadian Mind Products
Go to : punctuation 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z (all)
Files & Directories
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 or directory that may or may not actually exist.

Using new File( name ) Taking Apart A Filename Console I/O
Using new File( dir, name ) Permanent Files Applets
File Naming Temporary Files File I/O Amanuensis
Filename not URL Hints Learning More
Sample Code Locking Links
Manipulating Filenames and Files Platform Specific
Manipulating Directories Real World Platforms

Using new File( name )

File myFile = new File( "C:\\temp\\abc.txt" );

File myDir = new File( "/home/fundir" );

Using new 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" );

Filename not URL

gets you access to a file. You feed it a filename or directory name suitable for the native platform, not an URL. On windows, you can use / and \ interchangeably. \ has to be doubled because it is also the Java escape character.
// if E:\mindprod is a directory, then these
// four different ways of specifying it are
// all equivalent in Windows.
// You can use / or \ (coded as \\)
// You can optionally have a trailing / or \.
File dir1 = new File ( "E:\\mindprod" );
File dir2 = new File ( "E:\\mindprod\\" );
File dir3 = new File ( "E:/mindprod" );
File dir4 = new File ( "E:/mindprod/" );

If you need an URL or URI, you can use File.toURL or File.toURI.

Sample Code

Here is how you use most of the File methods. The listing comments also tell you what to expect from each of the methods, especially the many different ways you can get a file’s name.

Methods For Manipulating Filenames and Files

I have ordered these with the ones you are most likely to use near the top.

File.createNewFile

Atomically creates a new, empty file named if and only if a file with this name does not yet exist. Normally you don’t explicitly create the file. It is created as a side effect of writing to an OutputStream or Writer.

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 File.deleteOnExit. Can also be used to delete empty directories. delete() returns true if the file was successfully deleted, false if it did not exist, was already deleted or could not be deleted because it was in use or lack of sufficient privilege.

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. Coded as File.length() not File.length as you would with an array.

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
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 ). Windows keeps file timestamps accurate to 100 nanoseconds with 10,000 times as much precision as Java’s 1 ms. This means if you copy a file in Java, the new file might not have the exact same timestamp as the old. When you reconstitute a zipped file, its timestamp will be reconstituted accurate only to the even 2 seconds.

File.isFile

is there a file by this name? Is this file a true file rather than a directory?

RandomAccessFile.setLength

chop/grow this file to n bytes long. JDK 1.2+ only. You can’t use this directly on the File. You must create a RandomAccessFile object first with new RandomAccessFile( file, "rw" );

File.setReadOnly

Lets you make a file read-only. There is no way to undo this in Java.

File.setlastModified

set last modified timestamp. This happens anyway automatically when you modify and close a file. You cannot read or access the last access date or the create date without using the FileTimes class, jni or exec.

Manipulating Directories

The file methods work on directories. These methods are primarily for working on directories. File is used to represent both a directory and a 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. The lists include all files and directories, hidden or revealed. It is as if Java ignores the hidden attribute. If the directory is empty, you will get an empty list new String[0]. However, if the file you give it is not a directory or does not exist, you will get null.

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

File.isDirectory

is there a directory by this name. Is this file a directory rather than in individual file?

File.listRoots

a list of available drives, JDK 1.2+ only. Note it returns you an array of File objects, not Strings. If you print them, on Windows, they will have the form A:\. On Linux, there is only one root /

javax.swing.
filechooser.
FileSystemView.
getFileSystemView().
getRoots()

alternate way to get a list of available drives.

File.mkdirs

// Creating several levels of directory all in one pop as needed.
// Note mkdirs is an instance method, so you specify the directory tree
// to create in the File constructor.
final boolean success = new File( "C:/temp/wombats" ).mkdirs();

// That is single line is equivalent to:
final File dirs = new File( "C:/temp/wombats" );
final boolean success = dirs.mkdirs();
(It violates Sun’s naming conventions, but it is mk dirs, not mkDirs), make a directory and any necessary parent directories. mkdir is similar, but does not create parent directories. This is an instance method of File. You define the directory first with new File then create the tree. Returns true if all directory nodes were successfully created or were pre-existing. Returns false if it can’t complete the job. It may have created some but not all of the directories when it fails. If it succeeds you are certain they are all there.

Windows takes a short while after you make a successful mkdirs request to actually post the addition to the directory structure. So if you do an File.exists immediately afterward, it can sometimes fail. So close your eyes and trust the result of mkDirs. The directories will be there by the time you create and close a file.

File.getUsableSpace

JDK 1.6+, How much free space is on a drive/partition that is free for you to use.

File.getFreeSpace

JDK 1.6+, How much free space is on a drive/partition. You might not necessarily be allowed to write to all or any of it.

File.getTotalSpace

JDK 1.6+, How much free space is on a drive/partition combined used/unused.

Taking Apart A Filename:

There are strange filenames like C:\ . .. ../sub C:. Make sure you test that your code works with them as well. I have ordered this list with the ones you will use most often near the top. What you get depends on what you put in. Look at the sample code to see the fine points. Here I am presuming you put in minimal relative filenames.

File.toString

partially qualified directory + name + extension. If you do a System. out.println ( someFile ) you will get the toString version.

File.getAbsolutePath

fully qualified drive + 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.getName

just the name + extension.

File.getPath

partially qualified directory + name + extension.

File.getParent

partially qualified directory.
Uses \ instead of / for the separator in Windows. Only works gives you the absolute parent if you provide fully qualified filenames. 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 W95/W98/Me/NT/W2K/XP/W2K3/Vista. 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 W95/W98/Me/NT/W2K/XP/W2K3/Vista. Gets you the precise case.

File.isAbsolute

true if the file name is absolute, false if relative to the current directory.

Permanent Files

Finding a suitable spot to place permanent files is much more difficult than it should be. Here are some approaches.

Temporary Files

Here are the methods useful for manipulating temporary files.

File.createTempFile

Create a temporary file whose name is guaranteed to be unique. You specify a prefix, suffix and directory to use. Always name your temporary files with a prefix temp and a suffix .tmp so that they can easily be scavenged and deleted after a crash by generic junk cleaning utilities. To put the temporary in the same directory as another file, use getParent to find the directory. The file will not be automatically deleted on exit, unless you use deleteOnExit.
// creating a temporary file.
File temp = File .createTempFile( "temp", ".tmp", new File( "C:\\temp" ) );

// Arrange for this temporary file to be automatically deleted on exit
// if we forget to delete it.
temp.deleteOnExit();

File.deleteOnExit

Arrange for this temporary file to be automatically deleted on exit if we forget to.

File.delete

Delete the temporary file now.

Hints

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.
Peter van der Linden’s FAQ for more detail on file locking

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:
You are safest to build up filenames programmatically like this:
For WORA, it is best to use very conservative file naming conventions: Anything else is bound to confuse some OS somewhere.

Real World Platforms

Windows 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      
  1. Each directory or file component must be less than or equal to 12 characters.
  2. Both "." and ".." can be valid file names.
  3. The construct "." does not refer to the current directory.
  4. 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.

Learning More

Sun’s Javadoc on the File class : available:

CMP_homejump to top
CMP logo
feedback Please email your feedback for publication, errors, omissions, broken/redirected link reports
and suggestions to improve this page to Roedy Green : feedback email
made with CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[65.110.21.43]
Your face IP:[38.103.63.16] The information on this page is for non-military use only.
You are visitor number 205,245. Military use includes use by defence contractors.
You can get a fresh copy of this page from: or possibly from your local J: drive (Java virtual drive/Mindprod website mirror)
http://mindprod.com/jgloss/file.html J:\mindprod\jgloss\file.html