Java Reference
In-Depth Information
Keep in mind that a File object is similar to a String and only represents the path name
of a file or directory. The constructors are successful even if the given file or directory does
not exist. For example, the following statement is successful, whether or not somefile.txt is
an actual file:
File f = new File(“somefile.txt”);
However, you now have a File object associated with a file named somefile.txt, and the
File class contains many useful methods for determining information about this file. For
example, you can check to see if it exists using the exists() method:
if(f.exists())
{
//Use the file now that we know it exists
}
Other methods in the File class include:
public String getName().
Returns the name of the file or directory.
public String getParent().
Returns the pathname of the parent directory of this file
or directory.
public String getPath(). Returns the File object as its String representation.
public boolean canRead(). Returns true if the File object is a file that can be read
from. There is also a corresponding canWrite() method.
public boolean isDirectory(). Returns true if the File object is a directory.
public boolean isFile(). Returns true if the File object is a file.
public boolean delete(). Deletes the file or directory, and returns true if successful.
public String [] list(). Returns a list of all the filenames in the directory.
To demonstrate the File class, the following FileDemo program creates a File object and
uses the methods of the File class to determine information about the file or directory.
Study the program and see if you can determine what it does.
import java.io.File;
public class FileDemo
{
public static void main(String [] args)
{
File file = new File(args[0]);
if(!file.exists())
{
System.out.println(args[0]
+ “ does not exist.”);
return;
}
if(file.isFile() && file.canRead())
continued
Search WWH ::




Custom Search