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.
File myFile = new File( "C:\\temp\\abc.txt" ); File myDir = new File( "/home/fundir" );
new File ( ".", "C:/fileInRoot.txt" )if
new File ( "myDir", "/otherDir" )
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
new File ( "species", "clan/individual.txt" )and
new File ( "species/clan/individual.txt" );
Under the hood, File is surprisingly lightweight. It is just a String and an int to record the prefix length. The prefix is the drive specifier, or the lead /. There is no OS (Operating System) file handle of any kind. Since the current directory cannot change throughout the execution of a program, the File constructor does not need to embed it in each File object.
// this does not work. File base = new File ( "mydir/myfile.txt" ); File f2 = new File( base, "myfile2.txt" );to create a file mydir/myfile2.txt. This does not work. You will get mydir/myfile.txt/myfile2.txt instead.
// 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 (Uniform Resource Indicator), you can use File.toURL or File. toURI.
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. It won’t delete directories containing files or directories trees. You have to recurse the tree to remove files and branches one by one.
Apache Commons-io has a method called FileUtils.deleteDirectory()
that will delete a directory tree.
|
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.
renameTo could fail if:
|
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? It is not sufficient that you can create and write this file. 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 by 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 version 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.Java version 1.2 or later 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 (Java Native Interface) or exec. |
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. So whenever you use File.list() check for filenames == null before you do for ( String filename : filenames) 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,Java version 1.2 or later 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 //, so it is not useful to get you a list of mount points. |
javax.swing. |
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" ); // true if created dir, false if could not create, or already created. final boolean success = dirs.mkdirs();(It violates Oracle’s naming conventions, but it is mkdirs, 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. Returns false if it can’t complete the job, or if directories were already existing. It may have created some but not all of the directories when it fails. If it succeeds you are certain they are all there.
|
File.getUsableSpace |
Java version 1.6 or later, How much free space is on a drive/partition that is free for you to use. |
File.getFreeSpace |
Java version 1.6 or later, 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 |
Java version 1.6 or later, How much free space is on a drive/partition combined used/unused. |
File.toString |
partially qualified directory + core + extension. If you do a System. out. println ( someFile ) you will get the toString version. |
File.getAbsolutePath |
fully qualified drive + directory + core + 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 core + extension. For a directory gets the last leg of the directory name. |
File.getPath |
partially qualified directory + core + extension. |
File.getParent |
partially qualified directory. |
File.getCanonicalPath |
drive + fully qualified directory + core + extension. Uses \ instead of / for the separator in W95, W98, Me, NT, W2K, XP, W2003, Vista, W2008, W7-32, W7-64, W8-32, W8-64, W2012, W10-32 and W10-64. Gets you the precise case. May throw an IOException. To avoid that use the cruder getAbsolutePath. In canonical form on Windows, drive letters are upper case. |
File.getCanonicalFile |
drive + fully qualified directory + core + extension
packaged up in a new File Object. Uses \ instead of / for the separator in W95, W98, Me, NT, W2K, XP, W2003, Vista, W2008, W7-32, W7-64, W8-32, W8-64, W2012, W10-32 and W10-64. Gets you the precise case. In canonical form on Windows, drive letters are upper case. |
File.isAbsolute |
true if the file name is absolute, false if relative to the current directory. |
com.mindprod.common18.EIO.getExtension |
extension Gets the extension, the part of the filename after the dot. |
com.mindprod.common18.EIO.getCoreName |
core Gets the core, getName with the .extension chopped off, with no directory. |
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. |
File.deleteOnExit |
Arrange for this temporary file to be automatically deleted on exit if we forget to. This is more efficient than setting up a Runtime. getRuntime().addShutdownHook( new Thread(). There is no equivalent closeOnExit for various file |
File.delete |
Delete the temporary file now. |
The easiest way to deal with this is to use an SQL database manager which can deal with concurrent updates.
Windows | Linux | Apple iMac | Groupe Bull GCOS 8 (JDK (Java Development Kit) 1.1.6) | |
---|---|---|---|---|
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 |
|
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 |
This page is posted |
http://mindprod.com/jgloss/filesanddirectories.html | |
Optional Replicator mirror
|
J:\mindprod\jgloss\filesanddirectories.html | |
Please read the feedback from other visitors,
or send your own feedback about the site. Contact Roedy. Please feel free to link to this page without explicit permission. | ||
Canadian
Mind
Products
IP:[65.110.21.43] Your face IP:[3.141.198.13] |
| |
Feedback |
You are visitor number | |