Since the only place to which we’ve written any results in examples and exercises is to the system console, you’d be justified in wondering if Java can communicate in any other way. The time has come to delve into that very issue.
All input and output from any computer program comes in the form of streams. You may think of data in terms of lines of text or of fields, but it’s actually just an undelimited string–a stream–of characters. Where one line or field ends and another begins is entirely up to the software.
Of course, Java programs can send and receive data from disk files, databases, and via telecommunication. This lesson deals with the first.
The File Class
The Java documentation says class java.io.File is “an abstract representation of file and directory pathnames,” but that understates the case. To reach a disk file or directory, whether for input or output, you do indeed use class File. And the files and directories File instances describe might not exist and might never exist. But instances of this class do many tangible things themselves, such as creation, renaming, and deletion. The only thing they don’t do is actually read and write file content. These are done by Reader and Writer classes, to which Files are passed so they know from where to read or to where to write.
There are many more fields, constructors, and methods for File than you’re likely to use in practice, and you find them all at the link above. Here are those you’ll find most useful.
File constructors
File(String pathname)
Designates a file by complete path name. This syntax is most useful for input files whose complete pathnames are provided by, say, command line arguments or property files.
File(String parent, String child)
File(File parent, String child)
Designates a file by directory name (the parent) and a filename (child) within that directory. This is most useful for new output files, where the directory name is provided but the file name might be determined at runtime. If you use the first syntax, you needn’t worry about whether the parent name has a terminating slash; Java will construct the pathname correctly.
File methods
Method | Purpose |
boolean createNewFile() | Attempts to create the file as new. Returns true if the file did not already exist. This method isn’t necessary unless you need to replace an existing file. |
static File createTempFile(String prefix, String suffix) | Creates a temporary file in the system default temporary file directory, using the given prefix and suffix to generate its name, which is otherwise unpredictable. The suffix should end with the desired filename extension, e.g. “.txt”. See deleteOnExit() below. |
static File createTempFile(String prefix, String suffix, File directory) | Creates a temporary file in the specified directory, using the given prefix and suffix to generate its name, which is otherwise unpredictable. The suffix should end with the desired filename extension, e.g. “.txt”. See deleteOnExit() below. |
boolean delete() | Deletes the file if it exists and returns true. If the file did not exist, returns false. |
void deleteOnExit() | Ensures that the file is deleted when the JVM terminates. |
boolean exists() | Returns true if the file exists and false if not. |
File getAbsoluteFile() String getAbsolutePath() String getCanonicalPath() File getCanonicalFile() String getPath() String getFile() | Various ways of getting name information about the File. |
File getParentFile() | Returns the parent (i.e., containing directory) of the File, or null if there is no parent. Of course, the parent of the parent is its containing directory, and so on up to the root of the file system. |
boolean isFile() | Returns true if the File is a file, otherwise false. |
boolean isHidden() | Returns true if the File is a hidden file or directory, otherwise false. |
long lastModified() | Returns the time (milliseconds since Jan. 1, 1970) at which the file was last modified. |
long length() | Returns the length of the file. |
String[] list() File[] listFiles() | Returns a list of file names (list) or Files (listFiles) in the directory denoted by the File instance. |
String[] list(FilenameFilter filter) File[] listFiles(FilenameFilter filter) File[] listFiles(FileFilter filter) | Returns a list of file names (list) or Files (listFiles) in the directory denoted by the File instance that satisfy the filter. |
boolean mkDir() boolean mkDirs() | Creates a directory named by the File. For mkdir(), the parent directory must already exist. For mkdirs(), all necessary parent directories will be created–especially useful if the parent directory won’t be known to exist at runtime. Either one returns true if the new directory is created, and false if not (meaning it already exists). |
boolean renameTo(File dest) | Renames (and possibly moves) the file to the path and name specified by dest. Returns true if the operation succeeded, and false if not (e.g., the destination already exists). |
boolean canExecute() boolean canRead() boolean canWrite() | Returns true if the indicated file attribute is true, and false otherwise. |
boolean setExecutable(boolean executable) boolean setReadable(boolean readable) boolean setWriteable(boolean writeable) boolean setExecutable(boolean executable, boolean ownerOnly) boolean setReadable(boolean readable, boolean ownerOnly) boolean setWriteable(boolean writeable, boolean ownerOnly) | Sets the indicated file attribute to the value provided in the first argument. If ownerOnly is true, the setting applies only to the file owner. Returns true if the operation succeeds. |
boolean setReadOnly() | Sets the file to read-only (which can be undone by calling setWriteOnly()). Returns true if the operation succeeds and false otherwise. |
About FileFilter and FilenameFilter
You may have noticed that the listFiles() and listFileNames() methods have an optional argument: a FilenameFilter or a FileFilter. These are actual instances of classes you can pass to these methods to control whether a File or a filename is added to the array returned by these methods. Here’s an example of a FileFilter.
String directoryName = "./input";
File directory = new File(directoryName);
File[] fileList = directory.listFiles(
new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
}
);
Both FileFilter and FilenameFilter have a single required method: accept(). This method returns true if the file or filename should be returned from listFiles() or listFileNames(), and false if not. In this example, a file is accepted only if it’s a directory. The accept() method for listFileNames() has a file name for an argument instead of a File.
Notice how, rather than being created elsewhere (although it could be), the instance of FileFilter is created within the argument list passed to listFiles(). This is a not uncommon technique for filters, Comparators (which we’ll cover later when we discuss Lists), and similar executable artifacts with very short lifespans.
What You Need to Know
- The File class lets you designate files for input and output.
- File provides many methods for manipulation of the file system, but doesn’t directly read from or write to files.