Class File
- All Implemented Interfaces:
Serializable,Comparable<File>
public class File extends Object implements Serializable, Comparable<File>
The actual file referenced by a File may or may not exist. It may
also, despite the name File, be a directory or other non-regular
file.
This class provides limited functionality for getting/setting file permissions, file type, and last modified time.
On Android strings are converted to UTF-8 byte sequences when sending filenames to
the operating system, and byte sequences returned by the operating system (from the
various list methods) are converted to strings by decoding them as UTF-8
byte sequences.
- See Also:
Serializable,Comparable, Serialized Form
-
Field Summary
Fields Modifier and Type Field Description static StringpathSeparatorThe system-dependent string used to separate components in search paths (":").static charpathSeparatorCharThe system-dependent character used to separate components in search paths (':').static StringseparatorThe system-dependent string used to separate components in filenames ('/').static charseparatorCharThe system-dependent character used to separate components in filenames ('/'). -
Constructor Summary
Constructors Constructor Description File(File dir, String name)Constructs a new file using the specified directory and name.File(String path)Constructs a new file using the specified path.File(String dirPath, String name)Constructs a new File using the specified directory path and file name, placing a path separator between the two.File(URI uri)Constructs a new File using the path of the specified URI. -
Method Summary
Modifier and Type Method Description booleancanExecute()Tests whether or not this process is allowed to execute this file.booleancanRead()Indicates whether the current context is allowed to read from this file.booleancanWrite()Indicates whether the current context is allowed to write to this file.intcompareTo(File another)Returns the relative sort ordering of the paths for this file and the fileanother.booleancreateNewFile()Creates a new, empty file on the file system according to the path information stored in this file.static FilecreateTempFile(String prefix, String suffix)Creates an empty temporary file using the given prefix and suffix as part of the file name.static FilecreateTempFile(String prefix, String suffix, File directory)Creates an empty temporary file in the given directory using the given prefix and suffix as part of the file name.booleandelete()Deletes this file.voiddeleteOnExit()Schedules this file to be automatically deleted when the VM terminates normally.booleanequals(Object obj)Comparesobjto this file and returnstrueif they represent the same object using a path specific comparison.booleanexists()Returns a boolean indicating whether this file can be found on the underlying file system.FilegetAbsoluteFile()Returns a new file constructed using the absolute path of this file.StringgetAbsolutePath()Returns the absolute path of this file.FilegetCanonicalFile()Returns a new file created using the canonical path of this file.StringgetCanonicalPath()Returns the canonical path of this file.longgetFreeSpace()Returns the number of free bytes on the partition containing this path.StringgetName()Returns the name of the file or directory represented by this file.StringgetParent()Returns the pathname of the parent of this file.FilegetParentFile()Returns a new file made from the pathname of the parent of this file.StringgetPath()Returns the path of this file.longgetTotalSpace()Returns the total size in bytes of the partition containing this path.longgetUsableSpace()Returns the number of usable free bytes on the partition containing this path.inthashCode()Returns an integer hash code for the receiver.booleanisAbsolute()Indicates if this file's pathname is absolute.booleanisDirectory()Indicates if this file represents a directory on the underlying file system.booleanisFile()Indicates if this file represents a file on the underlying file system.booleanisHidden()Returns whether or not this file is a hidden file as defined by the operating system.longlastModified()Returns the time when this file was last modified, measured in milliseconds since January 1st, 1970, midnight.longlength()Returns the length of this file in bytes.String[]list()Returns an array of strings with the file names in the directory represented by this file.String[]list(FilenameFilter filter)Gets a list of the files in the directory represented by this file.File[]listFiles()Returns an array of files contained in the directory represented by this file.File[]listFiles(FileFilter filter)Gets a list of the files in the directory represented by this file.File[]listFiles(FilenameFilter filter)Gets a list of the files in the directory represented by this file.static File[]listRoots()Returns the file system roots.booleanmkdir()Creates the directory named by this file, assuming its parents exist.booleanmkdirs()Creates the directory named by this file, creating missing parent directories if necessary.booleanrenameTo(File newPath)Renames this file tonewPath.booleansetExecutable(boolean executable)Equivalent to setExecutable(executable, true).booleansetExecutable(boolean executable, boolean ownerOnly)Manipulates the execute permissions for the abstract path designated by this file.booleansetLastModified(long time)Sets the time this file was last modified, measured in milliseconds since January 1st, 1970, midnight.booleansetReadable(boolean readable)Equivalent to setReadable(readable, true).booleansetReadable(boolean readable, boolean ownerOnly)Manipulates the read permissions for the abstract path designated by this file.booleansetReadOnly()Equivalent to setWritable(false, false).booleansetWritable(boolean writable)Equivalent to setWritable(writable, true).booleansetWritable(boolean writable, boolean ownerOnly)Manipulates the write permissions for the abstract path designated by this file.StringtoString()Returns a string containing a concise, human-readable description of this file.URItoURI()Returns a Uniform Resource Identifier for this file.URLtoURL()Deprecated.
-
Field Details
-
separatorChar
public static final char separatorCharThe system-dependent character used to separate components in filenames ('/'). Use of this (rather than hard-coding '/') helps portability to other operating systems.This field is initialized from the system property "file.separator". Later changes to that property will have no effect on this field or this class.
-
separator
The system-dependent string used to separate components in filenames ('/'). SeeseparatorChar. -
pathSeparatorChar
public static final char pathSeparatorCharThe system-dependent character used to separate components in search paths (':'). This is used to split such things as the PATH environment variable and classpath system properties into lists of directories to be searched.This field is initialized from the system property "path.separator". Later changes to that property will have no effect on this field or this class.
-
pathSeparator
The system-dependent string used to separate components in search paths (":"). SeepathSeparatorChar.
-
-
Constructor Details
-
File
Constructs a new file using the specified directory and name.- Parameters:
dir- the directory where the file is stored.name- the file's name.- Throws:
NullPointerException- ifnameisnull.
-
File
Constructs a new file using the specified path.- Parameters:
path- the path to be used for the file.
-
File
Constructs a new File using the specified directory path and file name, placing a path separator between the two.- Parameters:
dirPath- the path to the directory where the file is stored.name- the file's name.- Throws:
NullPointerException- ifname == null.
-
File
Constructs a new File using the path of the specified URI.urineeds to be an absolute and hierarchical Unified Resource Identifier with file scheme and non-empty path component, but with undefined authority, query or fragment components.- Parameters:
uri- the Unified Resource Identifier that is used to construct this file.- Throws:
IllegalArgumentException- ifuridoes not comply with the conditions above.- See Also:
toURI(),URI
-
-
Method Details
-
listRoots
Returns the file system roots. On Android and other Unix systems, there is a single root,/. -
canExecute
public boolean canExecute()Tests whether or not this process is allowed to execute this file. Note that this is a best-effort result; the only way to be certain is to actually attempt the operation.- Returns:
trueif this file can be executed,falseotherwise.- Since:
- 1.6
-
canRead
public boolean canRead()Indicates whether the current context is allowed to read from this file.- Returns:
trueif this file can be read,falseotherwise.
-
canWrite
public boolean canWrite()Indicates whether the current context is allowed to write to this file.- Returns:
trueif this file can be written,falseotherwise.
-
compareTo
Returns the relative sort ordering of the paths for this file and the fileanother. The ordering is platform dependent.- Specified by:
compareToin interfaceComparable<File>- Parameters:
another- a file to compare this file to- Returns:
- an int determined by comparing the two paths. Possible values are described in the Comparable interface.
- See Also:
Comparable
-
delete
public boolean delete()Deletes this file. Directories must be empty before they will be deleted.Note that this method does not throw
IOExceptionon failure. Callers must check the return value.- Returns:
trueif this file was deleted,falseotherwise.
-
deleteOnExit
public void deleteOnExit()Schedules this file to be automatically deleted when the VM terminates normally.Note that on Android, the application lifecycle does not include VM termination, so calling this method will not ensure that files are deleted. Instead, you should use the most appropriate out of:
- Use a
finallyclause to manually invokedelete(). - Maintain your own set of files to delete, and process it at an appropriate point in your application's lifecycle.
- Use the Unix trick of deleting the file as soon as all readers and writers have opened it. No new readers/writers will be able to access the file, but all existing ones will still have access until the last one closes the file.
- Use a
-
equals
Comparesobjto this file and returnstrueif they represent the same object using a path specific comparison.- Overrides:
equalsin classObject- Parameters:
obj- the object to compare this file with.- Returns:
trueifobjis the same as this object,falseotherwise.- See Also:
Object.hashCode()
-
exists
public boolean exists()Returns a boolean indicating whether this file can be found on the underlying file system.- Returns:
trueif this file exists,falseotherwise.
-
getAbsolutePath
Returns the absolute path of this file. An absolute path is a path that starts at a root of the file system. On Android, there is only one root:/.A common use for absolute paths is when passing paths to a
Processas command-line arguments, to remove the requirement implied by relative paths, that the child must have the same working directory as its parent. -
getAbsoluteFile
Returns a new file constructed using the absolute path of this file. Equivalent tonew File(this.getAbsolutePath()). -
getCanonicalPath
Returns the canonical path of this file. An absolute path is one that begins at the root of the file system. A canonical path is an absolute path with symbolic links and references to "." or ".." resolved. If a path element does not exist (or is not searchable), there is a conflict between interpreting canonicalization as a textual operation (where "a/../b" is "b" even if "a" does not exist) .Most callers should use
getAbsolutePath()instead. A canonical path is significantly more expensive to compute, and not generally useful. The primary use for canonical paths is determining whether two paths point to the same file by comparing the canonicalized paths.It can be actively harmful to use a canonical path, specifically because canonicalization removes symbolic links. It's wise to assume that a symbolic link is present for a reason, and that that reason is because the link may need to change. Canonicalization removes this layer of indirection. Good code should generally avoid caching canonical paths.
- Returns:
- the canonical path of this file.
- Throws:
IOException- if an I/O error occurs.
-
getCanonicalFile
Returns a new file created using the canonical path of this file. Equivalent tonew File(this.getCanonicalPath()).- Returns:
- the new file constructed from this file's canonical path.
- Throws:
IOException- if an I/O error occurs.
-
getName
Returns the name of the file or directory represented by this file.- Returns:
- this file's name or an empty string if there is no name part in the file's path.
-
getParent
Returns the pathname of the parent of this file. This is the path up to but not including the last name.nullis returned if there is no parent.- Returns:
- this file's parent pathname or
null.
-
getParentFile
Returns a new file made from the pathname of the parent of this file. This is the path up to but not including the last name.nullis returned when there is no parent.- Returns:
- a new file representing this file's parent or
null.
-
getPath
Returns the path of this file. -
hashCode
public int hashCode()Returns an integer hash code for the receiver. Any two objects for whichequalsreturnstruemust return the same hash code.- Overrides:
hashCodein classObject- Returns:
- this files's hash value.
- See Also:
equals(java.lang.Object)
-
isAbsolute
public boolean isAbsolute()Indicates if this file's pathname is absolute. Whether a pathname is absolute is platform specific. On Android, absolute paths start with the character '/'.- Returns:
trueif this file's pathname is absolute,falseotherwise.- See Also:
getPath()
-
isDirectory
public boolean isDirectory()Indicates if this file represents a directory on the underlying file system.- Returns:
trueif this file is a directory,falseotherwise.
-
isFile
public boolean isFile()Indicates if this file represents a file on the underlying file system.- Returns:
trueif this file is a file,falseotherwise.
-
isHidden
public boolean isHidden()Returns whether or not this file is a hidden file as defined by the operating system. The notion of "hidden" is system-dependent. For Unix systems a file is considered hidden if its name starts with a ".". For Windows systems there is an explicit flag in the file system for this purpose.- Returns:
trueif the file is hidden,falseotherwise.
-
lastModified
public long lastModified()Returns the time when this file was last modified, measured in milliseconds since January 1st, 1970, midnight. Returns 0 if the file does not exist.- Returns:
- the time when this file was last modified.
-
setLastModified
public boolean setLastModified(long time)Sets the time this file was last modified, measured in milliseconds since January 1st, 1970, midnight.Note that this method does not throw
IOExceptionon failure. Callers must check the return value.- Parameters:
time- the last modification time for this file.- Returns:
trueif the operation is successful,falseotherwise.- Throws:
IllegalArgumentException- iftime < 0.
-
setReadOnly
public boolean setReadOnly()Equivalent to setWritable(false, false).- See Also:
setWritable(boolean, boolean)
-
setExecutable
public boolean setExecutable(boolean executable, boolean ownerOnly)Manipulates the execute permissions for the abstract path designated by this file.Note that this method does not throw
IOExceptionon failure. Callers must check the return value.- Parameters:
executable- To allow execute permission if true, otherwise disallowownerOnly- To manipulate execute permission only for owner if true, otherwise for everyone. The manipulation will apply to everyone regardless of this value if the underlying system does not distinguish owner and other users.- Returns:
- true if and only if the operation succeeded. If the user does not have permission to change the access permissions of this abstract pathname the operation will fail. If the underlying file system does not support execute permission and the value of executable is false, this operation will fail.
- Since:
- 1.6
-
setExecutable
public boolean setExecutable(boolean executable)Equivalent to setExecutable(executable, true).- Since:
- 1.6
- See Also:
setExecutable(boolean, boolean)
-
setReadable
public boolean setReadable(boolean readable, boolean ownerOnly)Manipulates the read permissions for the abstract path designated by this file.- Parameters:
readable- To allow read permission if true, otherwise disallowownerOnly- To manipulate read permission only for owner if true, otherwise for everyone. The manipulation will apply to everyone regardless of this value if the underlying system does not distinguish owner and other users.- Returns:
- true if and only if the operation succeeded. If the user does not have permission to change the access permissions of this abstract pathname the operation will fail. If the underlying file system does not support read permission and the value of readable is false, this operation will fail.
- Since:
- 1.6
-
setReadable
public boolean setReadable(boolean readable)Equivalent to setReadable(readable, true).- Since:
- 1.6
- See Also:
setReadable(boolean, boolean)
-
setWritable
public boolean setWritable(boolean writable, boolean ownerOnly)Manipulates the write permissions for the abstract path designated by this file.- Parameters:
writable- To allow write permission if true, otherwise disallowownerOnly- To manipulate write permission only for owner if true, otherwise for everyone. The manipulation will apply to everyone regardless of this value if the underlying system does not distinguish owner and other users.- Returns:
- true if and only if the operation succeeded. If the user does not have permission to change the access permissions of this abstract pathname the operation will fail.
- Since:
- 1.6
-
setWritable
public boolean setWritable(boolean writable)Equivalent to setWritable(writable, true).- Since:
- 1.6
- See Also:
setWritable(boolean, boolean)
-
length
public long length()Returns the length of this file in bytes. Returns 0 if the file does not exist. The result for a directory is not defined.- Returns:
- the number of bytes in this file.
-
list
Returns an array of strings with the file names in the directory represented by this file. The result isnullif this file is not a directory.The entries
.and..representing the current and parent directory are not returned as part of the list.- Returns:
- an array of strings with file names or
null.
-
list
Gets a list of the files in the directory represented by this file. This list is then filtered through a FilenameFilter and the names of files with matching names are returned as an array of strings. Returnsnullif this file is not a directory. Iffilterisnullthen all filenames match.The entries
.and..representing the current and parent directories are not returned as part of the list.- Parameters:
filter- the filter to match names against, may benull.- Returns:
- an array of files or
null.
-
listFiles
Returns an array of files contained in the directory represented by this file. The result isnullif this file is not a directory. The paths of the files in the array are absolute if the path of this file is absolute, they are relative otherwise.- Returns:
- an array of files or
null.
-
listFiles
Gets a list of the files in the directory represented by this file. This list is then filtered through a FilenameFilter and files with matching names are returned as an array of files. Returnsnullif this file is not a directory. Iffilterisnullthen all filenames match.The entries
.and..representing the current and parent directories are not returned as part of the list.- Parameters:
filter- the filter to match names against, may benull.- Returns:
- an array of files or
null.
-
listFiles
Gets a list of the files in the directory represented by this file. This list is then filtered through a FileFilter and matching files are returned as an array of files. Returnsnullif this file is not a directory. Iffilterisnullthen all files match.The entries
.and..representing the current and parent directories are not returned as part of the list.- Parameters:
filter- the filter to match names against, may benull.- Returns:
- an array of files or
null.
-
mkdir
public boolean mkdir()Creates the directory named by this file, assuming its parents exist. Usemkdirs()if you also want to create missing parents.Note that this method does not throw
IOExceptionon failure. Callers must check the return value. Note also that this method returns false if the directory already existed. If you want to know whether the directory exists on return, either use(f.mkdir() || f.isDirectory())or simply ignore the return value from this method and simply callisDirectory().- Returns:
trueif the directory was created,falseon failure or if the directory already existed.
-
mkdirs
public boolean mkdirs()Creates the directory named by this file, creating missing parent directories if necessary. Usemkdir()if you don't want to create missing parents.Note that this method does not throw
IOExceptionon failure. Callers must check the return value. Note also that this method returns false if the directory already existed. If you want to know whether the directory exists on return, either use(f.mkdirs() || f.isDirectory())or simply ignore the return value from this method and simply callisDirectory().- Returns:
trueif the directory was created,falseon failure or if the directory already existed.
-
createNewFile
Creates a new, empty file on the file system according to the path information stored in this file. This method returns true if it creates a file, false if the file already existed. Note that it returns false even if the file is not a file (because it's a directory, say).This method is not generally useful. For creating temporary files, use
createTempFile(java.lang.String, java.lang.String)instead. For reading/writing files, useFileInputStream,FileOutputStream, orRandomAccessFile, all of which can create files.Note that this method does not throw
IOExceptionif the file already exists, even if it's not a regular file. Callers should always check the return value, and may additionally want to callisFile().- Returns:
- true if the file has been created, false if it already exists.
- Throws:
IOException- if it's not possible to create the file.
-
createTempFile
Creates an empty temporary file using the given prefix and suffix as part of the file name. Ifsuffixis null,.tmpis used. This method is a convenience method that callscreateTempFile(String, String, File)with the third argument beingnull.- Parameters:
prefix- the prefix to the temp file name.suffix- the suffix to the temp file name.- Returns:
- the temporary file.
- Throws:
IOException- if an error occurs when writing the file.
-
createTempFile
Creates an empty temporary file in the given directory using the given prefix and suffix as part of the file name. Ifsuffixis null,.tmpis used.Note that this method does not call
deleteOnExit(), but see the documentation for that method before you call it manually.- Parameters:
prefix- the prefix to the temp file name.suffix- the suffix to the temp file name.directory- the location to which the temp file is to be written, ornullfor the default location for temporary files, which is taken from the "java.io.tmpdir" system property. It may be necessary to set this property to an existing, writable directory for this method to work properly.- Returns:
- the temporary file.
- Throws:
IllegalArgumentException- if the length ofprefixis less than 3.IOException- if an error occurs when writing the file.
-
renameTo
Renames this file tonewPath. This operation is supported for both files and directories.Many failures are possible. Some of the more likely failures include:
- Write permission is required on the directories containing both the source and destination paths.
- Search permission is required for all parents of both paths.
- Both paths be on the same mount point. On Android, applications are most likely to hit this restriction when attempting to copy between internal storage and an SD card.
Note that this method does not throw
IOExceptionon failure. Callers must check the return value.- Parameters:
newPath- the new path.- Returns:
- true on success.
-
toString
Returns a string containing a concise, human-readable description of this file. -
toURI
Returns a Uniform Resource Identifier for this file. The URI is system dependent and may not be transferable between different operating / file systems.- Returns:
- an URI for this file.
-
toURL
Deprecated.UsetoURI()andURI.toURL()to correctly escape illegal characters.Returns a Uniform Resource Locator for this file. The URL is system dependent and may not be transferable between different operating / file systems.- Returns:
- a URL for this file.
- Throws:
MalformedURLException- if the path cannot be transformed into a URL.
-
getTotalSpace
public long getTotalSpace()Returns the total size in bytes of the partition containing this path. Returns 0 if this path does not exist.- Since:
- 1.6
-
getUsableSpace
public long getUsableSpace()Returns the number of usable free bytes on the partition containing this path. Returns 0 if this path does not exist.Note that this is likely to be an optimistic over-estimate and should not be taken as a guarantee your application can actually write this many bytes. On Android (and other Unix-based systems), this method returns the number of free bytes available to non-root users, regardless of whether you're actually running as root, and regardless of any quota or other restrictions that might apply to the user. (The
getFreeSpacemethod returns the number of bytes potentially available to root.)- Since:
- 1.6
-
getFreeSpace
public long getFreeSpace()Returns the number of free bytes on the partition containing this path. Returns 0 if this path does not exist.Note that this is likely to be an optimistic over-estimate and should not be taken as a guarantee your application can actually write this many bytes.
- Since:
- 1.6
-
toURI()andURI.toURL()to correctly escape illegal characters.