Remove old autovect-branch by moving to "dead" directory.
[official-gcc.git] / old-autovect-branch / libjava / java / io / File.java
blobe3d59cb7d2465a03a0fe9169cc447feb5cbf04f7
1 /* File.java -- Class representing a file on disk
2 Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005
3 Free Software Foundation, Inc.
5 This file is part of GNU Classpath.
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING. If not, write to the
19 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 02110-1301 USA.
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library. Thus, the terms and
24 conditions of the GNU General Public License cover the whole
25 combination.
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module. An independent module is a module which is not derived from
34 or based on this library. If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so. If you do not wish to do so, delete this
37 exception statement from your version. */
40 package java.io;
42 import java.net.MalformedURLException;
43 import java.net.URI;
44 import java.net.URISyntaxException;
45 import java.net.URL;
46 import gnu.classpath.Configuration;
47 import gnu.gcj.runtime.FileDeleter;
49 /* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3
50 * "The Java Language Specification", ISBN 0-201-63451-1
51 * Status: Complete to version 1.3.
54 /**
55 * This class represents a file or directory on a local disk. It provides
56 * facilities for dealing with a variety of systems that use various
57 * types of path separators ("/" versus "\", for example). It also
58 * contains method useful for creating and deleting files and directories.
60 * @author Aaron M. Renn (arenn@urbanophile.com)
61 * @author Tom Tromey (tromey@cygnus.com)
63 public class File implements Serializable, Comparable
65 private static final long serialVersionUID = 301077366599181567L;
67 // QUERY arguments to access function.
68 private final static int READ = 0;
69 private final static int WRITE = 1;
70 private final static int EXISTS = 2;
72 // QUERY arguments to stat function.
73 private final static int DIRECTORY = 0;
74 private final static int ISFILE = 1;
75 private final static int ISHIDDEN = 2;
77 // QUERY arguments to attr function.
78 private final static int MODIFIED = 0;
79 private final static int LENGTH = 1;
81 private final native long attr (int query);
82 // On OSF1 V5.0, `stat' is a macro. It is easiest to use the name
83 // `_stat' instead. We do the same thing for `_access' just in
84 // case.
85 private final native boolean _access (int query);
86 private final native boolean _stat (int query);
88 /**
89 * This is the path separator string for the current host. This field
90 * contains the value of the <code>file.separator</code> system property.
91 * An example separator string would be "/" on the GNU system.
93 public static final String separator = System.getProperty("file.separator");
94 private static final String dupSeparator = separator + separator;
96 /**
97 * This is the first character of the file separator string. On many
98 * hosts (for example, on the GNU system), this represents the entire
99 * separator string. The complete separator string is obtained from the
100 * <code>file.separator</code>system property.
102 public static final char separatorChar = separator.charAt(0);
105 * This is the string that is used to separate the host name from the
106 * path name in paths than include the host name. It is the value of
107 * the <code>path.separator</code> system property.
109 public static final String pathSeparator
110 = System.getProperty("path.separator");
113 * This is the first character of the string used to separate the host name
114 * from the path name in paths that include a host. The separator string
115 * is taken from the <code>path.separator</code> system property.
117 public static final char pathSeparatorChar = pathSeparator.charAt(0);
119 static final String tmpdir = System.getProperty("java.io.tmpdir");
120 static int maxPathLen;
121 static boolean caseSensitive;
123 static
125 if (Configuration.INIT_LOAD_LIBRARY)
127 System.loadLibrary("javaio");
130 init_native();
133 // Native function called at class initialization. This should should
134 // set the maxPathLen and caseSensitive variables.
135 private static native void init_native();
138 * This is the path to the file set when the object is created. It
139 * may be an absolute or relative path name.
141 private String path;
143 // We keep a counter for use by createTempFile. We choose the first
144 // value randomly to try to avoid clashes with other VMs.
145 private static long counter = Double.doubleToLongBits (Math.random());
148 * This method tests whether or not the current thread is allowed to
149 * to read the file pointed to by this object. This will be true if and
150 * and only if 1) the file exists and 2) the <code>SecurityManager</code>
151 * (if any) allows access to the file via it's <code>checkRead</code>
152 * method 3) the file is readable.
154 * @return <code>true</code> if reading is allowed,
155 * <code>false</code> otherwise
157 * @exception SecurityException If the <code>SecurityManager</code>
158 * does not allow access to the file
160 public boolean canRead()
162 checkRead();
163 return _access (READ);
167 * This method test whether or not the current thread is allowed to
168 * write to this object. This will be true if and only if 1) The
169 * <code>SecurityManager</code> (if any) allows write access to the
170 * file and 2) The file exists and 3) The file is writable. To determine
171 * whether or not a non-existent file can be created, check the parent
172 * directory for write access.
174 * @return <code>true</code> if writing is allowed, <code>false</code>
175 * otherwise
177 * @exception SecurityException If the <code>SecurityManager</code>
178 * does not allow access to the file
180 public boolean canWrite()
182 checkWrite();
183 return _access (WRITE);
186 private native boolean performCreate() throws IOException;
189 * This method creates a new file of zero length with the same name as
190 * the path of this <code>File</code> object if an only if that file
191 * does not already exist.
192 * <p>
193 * A <code>SecurityManager.checkWrite</code> check is done prior
194 * to performing this action.
196 * @return <code>true</code> if the file was created, <code>false</code> if
197 * the file alread existed.
199 * @exception IOException If an I/O error occurs
200 * @exception SecurityException If the <code>SecurityManager</code> will
201 * not allow this operation to be performed.
203 * @since 1.2
205 public boolean createNewFile() throws IOException
207 checkWrite();
208 return performCreate();
212 * This native method handles the actual deleting of the file
214 private native boolean performDelete();
217 * This method deletes the file represented by this object. If this file
218 * is a directory, it must be empty in order for the delete to succeed.
220 * @return <code>true</code> if the file was deleted, <code>false</code>
221 * otherwise
223 * @exception SecurityException If deleting of the file is not allowed
225 public synchronized boolean delete()
227 SecurityManager s = System.getSecurityManager();
229 if (s != null)
230 s.checkDelete(path);
232 return performDelete();
236 * This method tests two <code>File</code> objects for equality by
237 * comparing the path of the specified <code>File</code> against the path
238 * of this object. The two objects are equal if an only if 1) The
239 * argument is not null 2) The argument is a <code>File</code> object and
240 * 3) The path of the <code>File</code>argument is equal to the path
241 * of this object.
242 * <p>
243 * The paths of the files are determined by calling the
244 * <code>getPath()</code>
245 * method on each object.
247 * @return <code>true</code> if the two objects are equal,
248 * <code>false</code> otherwise.
250 public boolean equals(Object obj)
252 if (! (obj instanceof File))
253 return false;
255 File other = (File) obj;
257 if (caseSensitive)
258 return path.equals(other.path);
259 else
260 return path.equalsIgnoreCase(other.path);
264 * This method tests whether or not the file represented by the object
265 * actually exists on the filesystem.
267 * @return <code>true</code> if the file exists, <code>false</code>otherwise.
269 * @exception SecurityException If reading of the file is not permitted
271 public boolean exists()
273 checkRead();
274 return _access (EXISTS);
278 * This method initializes a new <code>File</code> object to represent
279 * a file with the specified path.
281 * @param name The path name of the file
283 public File(String name)
285 path = normalizePath (name);
288 // Remove duplicate and redundant separator characters.
289 private String normalizePath(String p)
291 // On Windows, convert any '/' to '\'. This appears to be the same logic
292 // that Sun's Win32 Java performs.
293 if (separatorChar == '\\')
295 p = p.replace ('/', '\\');
296 // We have to special case the "\c:" prefix.
297 if (p.length() > 2 && p.charAt(0) == '\\' &&
298 ((p.charAt(1) >= 'a' && p.charAt(1) <= 'z') ||
299 (p.charAt(1) >= 'A' && p.charAt(1) <= 'Z')) &&
300 p.charAt(2) == ':')
301 p = p.substring(1);
304 int dupIndex = p.indexOf(dupSeparator);
305 int plen = p.length();
307 // Special case: permit Windows UNC path prefix.
308 if (dupSeparator.equals("\\\\") && dupIndex == 0)
309 dupIndex = p.indexOf(dupSeparator, 1);
311 if (dupIndex == -1)
313 // Ignore trailing separator (though on Windows "a:\", for
314 // example, is a valid and minimal path).
315 if (plen > 1 && p.charAt (plen - 1) == separatorChar)
317 if (! (separatorChar == '\\' && plen == 3 && p.charAt (1) == ':'))
318 return p.substring (0, plen - 1);
320 else
321 return p;
324 StringBuffer newpath = new StringBuffer(plen);
325 int last = 0;
326 while (dupIndex != -1)
328 newpath.append(p.substring(last, dupIndex));
329 // Ignore the duplicate path characters.
330 while (p.charAt(dupIndex) == separatorChar)
332 dupIndex++;
333 if (dupIndex == plen)
334 return newpath.toString();
336 newpath.append(separatorChar);
337 last = dupIndex;
338 dupIndex = p.indexOf(dupSeparator, last);
341 // Again, ignore possible trailing separator (except special cases
342 // like "a:\" on Windows).
343 int end;
344 if (plen > 1 && p.charAt (plen - 1) == separatorChar)
346 if (separatorChar == '\\' && plen == 3 && p.charAt (1) == ':')
347 end = plen;
348 else
349 end = plen - 1;
351 else
352 end = plen;
353 newpath.append(p.substring(last, end));
355 return newpath.toString();
359 * This method initializes a new <code>File</code> object to represent
360 * a file in the specified named directory. The path name to the file
361 * will be the directory name plus the separator string plus the file
362 * name. If the directory path name ends in the separator string, another
363 * separator string will still be appended.
365 * @param dirPath The path to the directory the file resides in
366 * @param name The name of the file
368 public File(String dirPath, String name)
370 if (name == null)
371 throw new NullPointerException();
372 if (dirPath != null)
374 if (dirPath.length() > 0)
376 // Try to be smart about the number of separator characters.
377 if (dirPath.charAt(dirPath.length() - 1) == separatorChar
378 || name.length() == 0)
379 path = normalizePath(dirPath + name);
380 else
381 path = normalizePath(dirPath + separatorChar + name);
383 else
385 // If dirPath is empty, use a system dependant
386 // default prefix.
387 // Note that the leading separators in name have
388 // to be chopped off, to prevent them forming
389 // a UNC prefix on Windows.
390 if (separatorChar == '\\' /* TODO use ON_WINDOWS */)
392 int skip = 0;
393 while(name.length() > skip
394 && (name.charAt(skip) == separatorChar
395 || name.charAt(skip) == '/'))
397 skip++;
399 name = name.substring(skip);
401 path = normalizePath(separatorChar + name);
404 else
405 path = normalizePath(name);
409 * This method initializes a new <code>File</code> object to represent
410 * a file in the specified directory. If the <code>directory</code>
411 * argument is <code>null</code>, the file is assumed to be in the
412 * current directory as specified by the <code>user.dir</code> system
413 * property
415 * @param directory The directory this file resides in
416 * @param name The name of the file
418 public File(File directory, String name)
420 this (directory == null ? null : directory.path, name);
424 * This method initializes a new <code>File</code> object to represent
425 * a file corresponding to the specified <code>file:</code> protocol URI.
427 * @param uri The uri.
429 public File(URI uri)
431 if (uri == null)
432 throw new NullPointerException("uri is null");
434 if (!uri.getScheme().equals("file"))
435 throw new IllegalArgumentException("invalid uri protocol");
437 String name = uri.getPath();
438 if (name == null)
439 throw new IllegalArgumentException("URI \"" + uri
440 + "\" is not hierarchical");
441 path = normalizePath(name);
445 * This method returns the path of this file as an absolute path name.
446 * If the path name is already absolute, then it is returned. Otherwise
447 * the value returned is the current directory plus the separatory
448 * string plus the path of the file. The current directory is determined
449 * from the <code>user.dir</code> system property.
451 * @return The absolute path of this file
453 public String getAbsolutePath()
455 if (isAbsolute())
456 return path;
457 else if (separatorChar == '\\'
458 && path.length() > 0 && path.charAt (0) == '\\')
460 // On Windows, even if the path starts with a '\\' it is not
461 // really absolute until we prefix the drive specifier from
462 // the current working directory to it.
463 return System.getProperty ("user.dir").substring (0, 2) + path;
465 else if (separatorChar == '\\'
466 && path.length() > 1 && path.charAt (1) == ':'
467 && ((path.charAt (0) >= 'a' && path.charAt (0) <= 'z')
468 || (path.charAt (0) >= 'A' && path.charAt (0) <= 'Z')))
470 // On Windows, a process has a current working directory for
471 // each drive and a path like "G:foo\bar" would mean the
472 // absolute path "G:\wombat\foo\bar" if "\wombat" is the
473 // working directory on the G drive.
474 String drvDir = null;
477 drvDir = new File (path.substring (0, 2)).getCanonicalPath();
479 catch (IOException e)
481 drvDir = path.substring (0, 2) + "\\";
484 // Note: this would return "C:\\." for the path "C:.", if "\"
485 // is the working folder on the C drive, but this is
486 // consistent with what Sun's JRE 1.4.1.01 actually returns!
487 if (path.length() > 2)
488 return drvDir + '\\' + path.substring (2, path.length());
489 else
490 return drvDir;
492 else
493 return System.getProperty ("user.dir") + separatorChar + path;
497 * This method returns a <code>File</code> object representing the
498 * absolute path of this object.
500 * @return A <code>File</code> with the absolute path of the object.
502 * @since 1.2
504 public File getAbsoluteFile()
506 return new File(getAbsolutePath());
510 * This method returns a canonical representation of the pathname of
511 * this file. The actual form of the canonical representation is
512 * different. On the GNU system, the canonical form differs from the
513 * absolute form in that all relative file references to "." and ".."
514 * are resolved and removed.
515 * <p>
516 * Note that this method, unlike the other methods which return path
517 * names, can throw an IOException. This is because native method
518 * might be required in order to resolve the canonical path
520 * @exception IOException If an error occurs
522 public native String getCanonicalPath() throws IOException;
525 * This method returns a <code>File</code> object representing the
526 * canonical path of this object.
528 * @return A <code>File</code> instance representing the canonical path of
529 * this object.
531 * @exception IOException If an error occurs.
533 * @since 1.2
535 public File getCanonicalFile() throws IOException
537 return new File(getCanonicalPath());
541 * This method returns the name of the file. This is everything in the
542 * complete path of the file after the last instance of the separator
543 * string.
545 * @return The file name
547 public String getName()
549 int nameSeqIndex = 0;
551 if (separatorChar == '\\' && path.length() > 1)
553 // On Windows, ignore the drive specifier or the leading '\\'
554 // of a UNC network path, if any (a.k.a. the "prefix").
555 if ((path.charAt (0) == '\\' && path.charAt (1) == '\\')
556 || (((path.charAt (0) >= 'a' && path.charAt (0) <= 'z')
557 || (path.charAt (0) >= 'A' && path.charAt (0) <= 'Z'))
558 && path.charAt (1) == ':'))
560 if (path.length() > 2)
561 nameSeqIndex = 2;
562 else
563 return "";
567 String nameSeq
568 = (nameSeqIndex > 0 ? path.substring (nameSeqIndex) : path);
570 int last = nameSeq.lastIndexOf (separatorChar);
572 return nameSeq.substring (last + 1);
576 * This method returns a <code>String</code> the represents this file's
577 * parent. <code>null</code> is returned if the file has no parent. The
578 * parent is determined via a simple operation which removes the
580 * @return The parent directory of this file
582 public String getParent()
584 String prefix = null;
585 int nameSeqIndex = 0;
587 // The "prefix", if present, is the leading "/" on UNIX and
588 // either the drive specifier (e.g. "C:") or the leading "\\"
589 // of a UNC network path on Windows.
590 if (separatorChar == '/' && path.charAt (0) == '/')
592 prefix = "/";
593 nameSeqIndex = 1;
595 else if (separatorChar == '\\' && path.length() > 1)
597 if ((path.charAt (0) == '\\' && path.charAt (1) == '\\')
598 || (((path.charAt (0) >= 'a' && path.charAt (0) <= 'z')
599 || (path.charAt (0) >= 'A' && path.charAt (0) <= 'Z'))
600 && path.charAt (1) == ':'))
602 prefix = path.substring (0, 2);
603 nameSeqIndex = 2;
607 // According to the JDK docs, the returned parent path is the
608 // portion of the name sequence before the last separator
609 // character, if found, prefixed by the prefix, otherwise null.
610 if (nameSeqIndex < path.length())
612 String nameSeq = path.substring (nameSeqIndex, path.length());
613 int last = nameSeq.lastIndexOf (separatorChar);
614 if (last == -1)
615 return prefix;
616 else if (last == (nameSeq.length() - 1))
617 // Note: The path would not have a trailing separator
618 // except for cases like "C:\" on Windows (see
619 // normalizePath( )), where Sun's JRE 1.4 returns null.
620 return null;
621 else if (last == 0)
622 last++;
624 if (prefix != null)
625 return prefix + nameSeq.substring (0, last);
626 else
627 return nameSeq.substring (0, last);
629 else
630 // Sun's JRE 1.4 returns null if the prefix is the only
631 // component of the path - so "/" gives null on UNIX and
632 // "C:", "\\", etc. return null on Windows.
633 return null;
637 * This method returns a <code>File</code> object representing the parent
638 * file of this one.
640 * @return a <code>File</code> for the parent of this object.
641 * <code>null</code>
642 * will be returned if this object does not have a parent.
644 * @since 1.2
646 public File getParentFile()
648 String parent = getParent();
649 return parent != null ? new File(parent) : null;
653 * Returns the path name that represents this file. May be a relative
654 * or an absolute path name
656 * @return The pathname of this file
658 public String getPath()
660 return path;
664 * This method returns a hash code representing this file. It is the
665 * hash code of the path of this file (as returned by <code>getPath()</code>)
666 * exclusived or-ed with the value 1234321.
668 * @return The hash code for this object
670 public int hashCode()
672 if (caseSensitive)
673 return path.hashCode() ^ 1234321;
674 else
675 return path.toLowerCase().hashCode() ^ 1234321;
679 * This method returns true if this object represents an absolute file
680 * path and false if it does not. The definition of an absolute path varies
681 * by system. As an example, on GNU systems, a path is absolute if it starts
682 * with a "/".
684 * @return <code>true</code> if this object represents an absolute
685 * file name, <code>false</code> otherwise.
687 public native boolean isAbsolute();
690 * This method tests whether or not the file represented by this object
691 * is a directory. In order for this method to return <code>true</code>,
692 * the file represented by this object must exist and be a directory.
694 * @return <code>true</code> if this file is a directory, <code>false</code>
695 * otherwise
697 * @exception SecurityException If reading of the file is not permitted
699 public boolean isDirectory()
701 checkRead();
702 return _stat (DIRECTORY);
706 * This method tests whether or not the file represented by this object
707 * is a "plain" file. A file is a plain file if and only if it 1) Exists,
708 * 2) Is not a directory or other type of special file.
710 * @return <code>true</code> if this is a plain file, <code>false</code>
711 * otherwise
713 * @exception SecurityException If reading of the file is not permitted
715 public boolean isFile()
717 checkRead();
718 return _stat (ISFILE);
722 * This method tests whether or not this file represents a "hidden" file.
723 * On GNU systems, a file is hidden if its name begins with a "."
724 * character. Files with these names are traditionally not shown with
725 * directory listing tools.
727 * @return <code>true</code> if the file is hidden, <code>false</code>
728 * otherwise.
730 * @since 1.2
732 public boolean isHidden()
734 checkRead();
735 return _stat (ISHIDDEN);
739 * This method returns the last modification time of this file. The
740 * time value returned is an abstract value that should not be interpreted
741 * as a specified time value. It is only useful for comparing to other
742 * such time values returned on the same system. In that case, the larger
743 * value indicates a more recent modification time.
744 * <p>
745 * If the file does not exist, then a value of 0 is returned.
747 * @return The last modification time of the file
749 * @exception SecurityException If reading of the file is not permitted
751 public long lastModified()
753 checkRead();
754 return attr (MODIFIED);
758 * This method returns the length of the file represented by this object,
759 * or 0 if the specified file does not exist.
761 * @return The length of the file
763 * @exception SecurityException If reading of the file is not permitted
765 public long length()
767 checkRead();
768 return attr (LENGTH);
772 * This native function actually produces the list of file in this
773 * directory
775 private final native Object[] performList (FilenameFilter filter,
776 FileFilter fileFilter,
777 Class result_type);
780 * This method returns a array of <code>String</code>'s representing the
781 * list of files is then directory represented by this object. If this
782 * object represents a non-directory file or a non-existent file, then
783 * <code>null</code> is returned. The list of files will not contain
784 * any names such as "." or ".." which indicate the current or parent
785 * directory. Also, the names are not guaranteed to be sorted.
786 * <p>
787 * In this form of the <code>list()</code> method, a filter is specified
788 * that allows the caller to control which files are returned in the
789 * list. The <code>FilenameFilter</code> specified is called for each
790 * file returned to determine whether or not that file should be included
791 * in the list.
792 * <p>
793 * A <code>SecurityManager</code> check is made prior to reading the
794 * directory. If read access to the directory is denied, an exception
795 * will be thrown.
797 * @param filter An object which will identify files to exclude from
798 * the directory listing.
800 * @return An array of files in the directory, or <code>null</code>
801 * if this object does not represent a valid directory.
803 * @exception SecurityException If read access is not allowed to the
804 * directory by the <code>SecurityManager</code>
806 public String[] list(FilenameFilter filter)
808 checkRead();
809 return (String[]) performList (filter, null, String.class);
813 * This method returns a array of <code>String</code>'s representing the
814 * list of files is then directory represented by this object. If this
815 * object represents a non-directory file or a non-existent file, then
816 * <code>null</code> is returned. The list of files will not contain
817 * any names such as "." or ".." which indicate the current or parent
818 * directory. Also, the names are not guaranteed to be sorted.
819 * <p>
820 * A <code>SecurityManager</code> check is made prior to reading the
821 * directory. If read access to the directory is denied, an exception
822 * will be thrown.
824 * @return An array of files in the directory, or <code>null</code> if
825 * this object does not represent a valid directory.
827 * @exception SecurityException If read access is not allowed to the
828 * directory by the <code>SecurityManager</code>
830 public String[] list()
832 checkRead();
833 return (String[]) performList (null, null, String.class);
837 * This method returns an array of <code>File</code> objects representing
838 * all the files in the directory represented by this object. If this
839 * object does not represent a directory, <code>null</code> is returned.
840 * Each of the returned <code>File</code> object is constructed with this
841 * object as its parent.
842 * <p>
843 * A <code>SecurityManager</code> check is made prior to reading the
844 * directory. If read access to the directory is denied, an exception
845 * will be thrown.
847 * @return An array of <code>File</code> objects for this directory.
849 * @exception SecurityException If the <code>SecurityManager</code> denies
850 * access to this directory.
852 * @since 1.2
854 public File[] listFiles()
856 checkRead();
857 return (File[]) performList (null, null, File.class);
861 * This method returns an array of <code>File</code> objects representing
862 * all the files in the directory represented by this object. If this
863 * object does not represent a directory, <code>null</code> is returned.
864 * Each of the returned <code>File</code> object is constructed with this
865 * object as its parent.
866 * <p>
867 * In this form of the <code>listFiles()</code> method, a filter is specified
868 * that allows the caller to control which files are returned in the
869 * list. The <code>FilenameFilter</code> specified is called for each
870 * file returned to determine whether or not that file should be included
871 * in the list.
872 * <p>
873 * A <code>SecurityManager</code> check is made prior to reading the
874 * directory. If read access to the directory is denied, an exception
875 * will be thrown.
877 * @return An array of <code>File</code> objects for this directory.
879 * @exception SecurityException If the <code>SecurityManager</code> denies
880 * access to this directory.
882 * @since 1.2
884 public File[] listFiles(FilenameFilter filter)
886 checkRead();
887 return (File[]) performList (filter, null, File.class);
891 * This method returns an array of <code>File</code> objects representing
892 * all the files in the directory represented by this object. If this
893 * object does not represent a directory, <code>null</code> is returned.
894 * Each of the returned <code>File</code> object is constructed with this
895 * object as its parent.
896 * <p>
897 * In this form of the <code>listFiles()</code> method, a filter is specified
898 * that allows the caller to control which files are returned in the
899 * list. The <code>FileFilter</code> specified is called for each
900 * file returned to determine whether or not that file should be included
901 * in the list.
902 * <p>
903 * A <code>SecurityManager</code> check is made prior to reading the
904 * directory. If read access to the directory is denied, an exception
905 * will be thrown.
907 * @return An array of <code>File</code> objects for this directory.
909 * @exception SecurityException If the <code>SecurityManager</code> denies
910 * access to this directory.
912 * @since 1.2
914 public File[] listFiles(FileFilter filter)
916 checkRead();
917 return (File[]) performList (null, filter, File.class);
921 * This method returns a <code>String</code> that is the path name of the
922 * file as returned by <code>getPath</code>.
924 * @return A <code>String</code> representation of this file
926 public String toString()
928 return path;
932 * @return A <code>URI</code> for this object.
934 public URI toURI()
936 String abspath = getAbsolutePath();
938 if (isDirectory())
939 abspath = abspath + separator;
943 return new URI("file", abspath.replace(separatorChar, '/'), null);
945 catch (URISyntaxException use)
947 // Can't happen.
948 throw new RuntimeException(use);
953 * This method returns a <code>URL</code> with the <code>file:</code>
954 * protocol that represents this file. The exact form of this URL is
955 * system dependent.
957 * @return A <code>URL</code> for this object.
959 * @exception MalformedURLException If the URL cannot be created
960 * successfully.
962 public URL toURL() throws MalformedURLException
964 // On Win32, Sun's JDK returns URLs of the form "file:/c:/foo/bar.txt",
965 // while on UNIX, it returns URLs of the form "file:/foo/bar.txt".
966 if (separatorChar == '\\')
967 return new URL ("file:/" + getAbsolutePath().replace ('\\', '/')
968 + (isDirectory() ? "/" : ""));
969 else
970 return new URL ("file:" + getAbsolutePath()
971 + (isDirectory() ? "/" : ""));
975 * This native method actually creates the directory
977 private final native boolean performMkdir();
980 * This method creates a directory for the path represented by this object.
982 * @return <code>true</code> if the directory was created,
983 * <code>false</code> otherwise
985 * @exception SecurityException If write access is not allowed to this file
987 public boolean mkdir()
989 checkWrite();
990 return performMkdir();
993 private static boolean mkdirs (File x)
995 if (x.isDirectory())
996 return true;
997 String p = x.getPath();
998 String parent = x.getParent();
999 if (parent != null)
1001 x.path = parent;
1002 if (! mkdirs (x))
1003 return false;
1004 x.path = p;
1006 return x.mkdir();
1010 * This method creates a directory for the path represented by this file.
1011 * It will also create any intervening parent directories if necessary.
1013 * @return <code>true</code> if the directory was created,
1014 * <code>false</code> otherwise
1016 * @exception SecurityException If write access is not allowed to this file
1018 public boolean mkdirs()
1020 checkWrite();
1021 if (isDirectory())
1022 return false;
1023 return mkdirs (new File (path));
1026 private static synchronized String nextValue()
1028 return Long.toString(counter++, Character.MAX_RADIX);
1032 * This method creates a temporary file in the specified directory. If
1033 * the directory name is null, then this method uses the system temporary
1034 * directory. The files created are guaranteed not to currently exist and
1035 * the same file name will never be used twice in the same virtual
1036 * machine instance.
1037 * The system temporary directory is determined by examinging the
1038 * <code>java.io.tmpdir</code> system property.
1039 * <p>
1040 * The <code>prefix</code> parameter is a sequence of at least three
1041 * characters that are used as the start of the generated filename. The
1042 * <code>suffix</code> parameter is a sequence of characters that is used
1043 * to terminate the file name. This parameter may be <code>null</code>
1044 * and if it is, the suffix defaults to ".tmp".
1045 * <p>
1046 * If a <code>SecurityManager</code> exists, then its <code>checkWrite</code>
1047 * method is used to verify that this operation is permitted.
1049 * @param prefix The character prefix to use in generating the path name.
1050 * @param suffix The character suffix to use in generating the path name.
1051 * @param directory The directory to create the file in, or
1052 * <code>null</code> for the default temporary directory
1054 * @exception IllegalArgumentException If the patterns is not valid
1055 * @exception SecurityException If there is no permission to perform
1056 * this operation
1057 * @exception IOException If an error occurs
1059 * @since 1.2
1061 public static File createTempFile(String prefix, String suffix,
1062 File directory)
1063 throws IOException
1065 // Grab the system temp directory if necessary
1066 if (directory == null)
1068 String dirname = tmpdir;
1069 if (dirname == null)
1070 throw new IOException("Cannot determine system temporary directory");
1072 directory = new File(dirname);
1073 if (!directory.exists())
1074 throw new IOException("System temporary directory "
1075 + directory.getName() + " does not exist.");
1076 if (!directory.isDirectory())
1077 throw new IOException("System temporary directory "
1078 + directory.getName()
1079 + " is not really a directory.");
1082 // Check if prefix is at least 3 characters long
1083 if (prefix.length() < 3)
1084 throw new IllegalArgumentException("Prefix too short: " + prefix);
1086 // Set default value of suffix
1087 if (suffix == null)
1088 suffix = ".tmp";
1090 // Truncation rules.
1091 // `6' is the number of characters we generate.
1092 if (prefix.length() + 6 + suffix.length() > maxPathLen)
1094 int suf_len = 0;
1095 if (suffix.charAt(0) == '.')
1096 suf_len = 4;
1097 suffix = suffix.substring(0, suf_len);
1098 if (prefix.length() + 6 + suf_len > maxPathLen)
1099 prefix = prefix.substring(0, maxPathLen - 6 - suf_len);
1102 File f;
1104 // How many times should we try? We choose 100.
1105 for (int i = 0; i < 100; ++i)
1107 // This is ugly.
1108 String t = "ZZZZZZ" + nextValue();
1109 String l = prefix + t.substring(t.length() - 6) + suffix;
1112 f = new File(directory, l);
1113 if (f.createNewFile())
1114 return f;
1116 catch (IOException ignored)
1121 throw new IOException ("cannot create temporary file");
1125 * This native method sets the permissions to make the file read only.
1127 private native boolean performSetReadOnly();
1130 * This method sets the file represented by this object to be read only.
1131 * A read only file or directory cannot be modified. Please note that
1132 * GNU systems allow read only files to be deleted if the directory it
1133 * is contained in is writable.
1135 * @return <code>true</code> if the operation succeeded, <code>false</code>
1136 * otherwise.
1138 * @exception SecurityException If the <code>SecurityManager</code> does
1139 * not allow this operation.
1141 * @since 1.2
1143 public boolean setReadOnly()
1145 // Do a security check before trying to do anything else.
1146 checkWrite();
1147 return performSetReadOnly();
1150 private static native File[] performListRoots();
1153 * This method returns an array of filesystem roots. Some operating systems
1154 * have volume oriented filesystem. This method provides a mechanism for
1155 * determining which volumes exist. GNU systems use a single hierarchical
1156 * filesystem, so will have only one "/" filesystem root.
1158 * @return An array of <code>File</code> objects for each filesystem root
1159 * available.
1161 * @since 1.2
1163 public static File[] listRoots()
1165 File[] roots = performListRoots();
1167 SecurityManager s = System.getSecurityManager();
1168 if (s != null)
1170 // Only return roots to which the security manager permits read access.
1171 int count = roots.length;
1172 for (int i = 0; i < roots.length; i++)
1176 s.checkRead (roots[i].path);
1178 catch (SecurityException sx)
1180 roots[i] = null;
1181 count--;
1184 if (count != roots.length)
1186 File[] newRoots = new File[count];
1187 int k = 0;
1188 for (int i=0; i < roots.length; i++)
1190 if (roots[i] != null)
1191 newRoots[k++] = roots[i];
1193 roots = newRoots;
1196 return roots;
1200 * This method creates a temporary file in the system temporary directory.
1201 * The files created are guaranteed not to currently exist and the same file
1202 * name will never be used twice in the same virtual machine instance. The
1203 * system temporary directory is determined by examinging the
1204 * <code>java.io.tmpdir</code> system property.
1205 * <p>
1206 * The <code>prefix</code> parameter is a sequence of at least three
1207 * characters that are used as the start of the generated filename. The
1208 * <code>suffix</code> parameter is a sequence of characters that is used
1209 * to terminate the file name. This parameter may be <code>null</code>
1210 * and if it is, the suffix defaults to ".tmp".
1211 * <p>
1212 * If a <code>SecurityManager</code> exists, then its <code>checkWrite</code>
1213 * method is used to verify that this operation is permitted.
1214 * <p>
1215 * This method is identical to calling
1216 * <code>createTempFile(prefix, suffix, null)</code>.
1218 * @param prefix The character prefix to use in generating the path name.
1219 * @param suffix The character suffix to use in generating the path name.
1221 * @exception IllegalArgumentException If the prefix or suffix are not valid.
1222 * @exception SecurityException If there is no permission to perform
1223 * this operation
1224 * @exception IOException If an error occurs
1226 public static File createTempFile(String prefix, String suffix)
1227 throws IOException
1229 return createTempFile(prefix, suffix, null);
1233 * This method compares the specified <code>File</code> to this one
1234 * to test for equality. It does this by comparing the canonical path names
1235 * of the files.
1236 * <p>
1237 * The canonical paths of the files are determined by calling the
1238 * <code>getCanonicalPath</code> method on each object.
1239 * <p>
1240 * This method returns a 0 if the specified <code>Object</code> is equal
1241 * to this one, a negative value if it is less than this one
1242 * a positive value if it is greater than this one.
1244 * @return An integer as described above
1246 * @since 1.2
1248 public int compareTo(File other)
1250 if (caseSensitive)
1251 return path.compareTo (other.path);
1252 else
1253 return path.compareToIgnoreCase (other.path);
1257 * This method compares the specified <code>Object</code> to this one
1258 * to test for equality. It does this by comparing the canonical path names
1259 * of the files. This method is identical to <code>compareTo(File)</code>
1260 * except that if the <code>Object</code> passed to it is not a
1261 * <code>File</code>, it throws a <code>ClassCastException</code>
1262 * <p>
1263 * The canonical paths of the files are determined by calling the
1264 * <code>getCanonicalPath</code> method on each object.
1265 * <p>
1266 * This method returns a 0 if the specified <code>Object</code> is equal
1267 * to this one, a negative value if it is less than this one
1268 * a positive value if it is greater than this one.
1270 * @return An integer as described above
1272 * @exception ClassCastException If the passed <code>Object</code> is
1273 * not a <code>File</code>
1275 * @since 1.2
1277 public int compareTo(Object obj)
1279 return compareTo((File) obj);
1283 * This native method actually performs the rename.
1285 private native boolean performRenameTo (File dest);
1288 * This method renames the file represented by this object to the path
1289 * of the file represented by the argument <code>File</code>.
1291 * @param dest The <code>File</code> object representing the target name
1293 * @return <code>true</code> if the rename succeeds, <code>false</code>
1294 * otherwise.
1296 * @exception SecurityException If write access is not allowed to the
1297 * file by the <code>SecurityMananger</code>.
1299 public synchronized boolean renameTo(File dest)
1301 SecurityManager s = System.getSecurityManager();
1302 String sname = getName();
1303 String dname = dest.getName();
1304 if (s != null)
1306 s.checkWrite (sname);
1307 s.checkWrite (dname);
1309 return performRenameTo (dest);
1313 * This method does the actual setting of the modification time.
1315 private native boolean performSetLastModified(long time);
1318 * This method sets the modification time on the file to the specified
1319 * value. This is specified as the number of seconds since midnight
1320 * on January 1, 1970 GMT.
1322 * @param time The desired modification time.
1324 * @return <code>true</code> if the operation succeeded, <code>false</code>
1325 * otherwise.
1327 * @exception IllegalArgumentException If the specified time is negative.
1328 * @exception SecurityException If the <code>SecurityManager</code> will
1329 * not allow this operation.
1331 * @since 1.2
1333 public boolean setLastModified(long time)
1335 if (time < 0)
1336 throw new IllegalArgumentException("Negative modification time: " + time);
1338 checkWrite();
1339 return performSetLastModified(time);
1342 private void checkWrite()
1344 // Check the SecurityManager
1345 SecurityManager s = System.getSecurityManager();
1347 if (s != null)
1348 s.checkWrite(path);
1351 private void checkRead()
1353 // Check the SecurityManager
1354 SecurityManager s = System.getSecurityManager();
1356 if (s != null)
1357 s.checkRead(path);
1360 /**
1361 * Calling this method requests that the file represented by this object
1362 * be deleted when the virtual machine exits. Note that this request cannot
1363 * be cancelled. Also, it will only be carried out if the virtual machine
1364 * exits normally.
1366 * @exception SecurityException If deleting of the file is not allowed
1368 * @since 1.2
1370 // FIXME: This should use the ShutdownHook API once we implement that.
1371 public void deleteOnExit()
1373 // Check the SecurityManager
1374 SecurityManager sm = System.getSecurityManager();
1375 if (sm != null)
1376 sm.checkDelete (getName());
1378 FileDeleter.add (this);
1381 private void writeObject(ObjectOutputStream oos) throws IOException
1383 oos.defaultWriteObject();
1384 oos.writeChar(separatorChar);
1387 private void readObject(ObjectInputStream ois)
1388 throws ClassNotFoundException, IOException
1390 ois.defaultReadObject();
1392 // If the file was from an OS with a different dir separator,
1393 // fixup the path to use the separator on this OS.
1394 char oldSeparatorChar = ois.readChar();
1396 if (oldSeparatorChar != separatorChar)
1397 path = path.replace(oldSeparatorChar, separatorChar);
1400 } // class File