File Class

Package: java.io

The File class represents a single file or directory. You can use the File class for basic file-manipulation tasks such as creating new files, deleting files, renaming files, and so on.

It’s important to understand that the File object represents a file that may or may not actually exist on disk. For example, to create a file on disk, you first create a File object for the file. Then, you call the File object’s createNewFile method to actually create the file on disk.

tip.eps Java 1.7 introduces a new Path class, which is designed to replace the File class. For more information, see Path Class.

Constructor

Constructor

Description

File(String pathname)

Creates a file with the specified pathname.

To create a File object, you call the File constructor, passing a string representing the filename as a parameter. Here’s an example:

File f = new File(“myfile.txt”);

Here, the file’s name is myfile.txt, and it lives in the current directory, which usually is the directory from which the Java Virtual Machine (JVM) was started.

If you want to use a directory other than the current directory, you must supply a complete pathname in the parameter string. Bear in mind that pathnames are system-dependent. For example, c:mydifectorymyfile.txt is valid for Windows systems, for example, but not on Unix or Macintosh systems, which don’t use drive letters and use forward slashes instead of backslashes to separate directories.

Methods

Method

Description

boolean canRead()

Determines whether the file can be read.

boolean canWrite()

Determines whether the file can be written.

boolean createNewFile()

Creates the file on the hard drive if it doesn’t exist. The method returns true if the file was created or false if the file already existed and throws IOException.

boolean delete()

Deletes the file or directory. The method returns true if the file was deleted successfully.

boolean exists()

Returns true if the file exists on the hard drive and false if the file doesn’t exist.

String getCanonicalPath()

Returns the complete path to the file, including the drive letter if run on a Windows system; throws IOException.

String getName()

Gets the name of this file.

String getParent()

Gets the name of the parent directory of this file or directory.

File getParentFile()

Gets a File object representing the parent directory of this file or directory.

boolean isDirectory()

Returns true if this File object is a directory or false if it is a file.

boolean isFile()

Returns true if this File object is a file or false if it is a directory.

boolean isHidden()

Returns true if this file or directory is marked by the operating system as hidden.

long lastModified()

Returns the time when the file was last modified, expressed in milliseconds since 0:00:00 a.m., January 1, 1970.

long length()

Returns the size of the file in bytes.

String[] list()

Returns an array of String objects with the name of each file and directory in this directory. Each string is a simple filename, not a complete path. If this File object is not a directory, the method returns null.

File[] listFiles()

Returns an array of File objects representing each file and directory in this directory. If this File object is not a directory, the method returns null.

static File[] listRoots()

Returns an array containing a File object for the root directory of every file system available on the Java runtime. Unix systems usually have just one root, but Windows systems have a root for each drive.

boolean mkdir()

Creates a directory on the hard drive from this File object. The method returns true if the directory was created successfully.

boolean mkdirs()

Creates a directory on the hard drive from this File object, including any parent directories that are listed in the directory path but don’t already exist. The method returns true if the directory was created successfully.

boolean renameTo(File dest)

Renames the File object to the specified destination File object. The method returns true if the rename was successful.

boolean setLastModified(long time)

Sets the last modified time for the File object. The method returns true if the time was set successfully.

boolean setReadOnly()

Marks the file as read-only. The method returns true if the file was marked successfully.

String toString()

Returns the pathname for this file or directory as a string.

Creating a file

Creating an instance of the File class does not create a file on disk; it merely creates an in-memory object that represents a file or directory that may or may not actually exist on disk. To find out whether the file or directory exists, you can use the exists method, as in this example:

File f = new File(path);

if (!f.exists())

System.out.println

(“The input file does not exist!”);

Here, a message is displayed on the console if the file doesn’t exist.

To create a new file on the hard drive, you must create a File instance with the filename you want to use and then use the createNewFile method, like this:

File f = new File(path);

f.createNewFile();

The createNewFile method returns a Boolean value that indicates whether the file was created successfully. If the file already exists, createNewFile returns false or if the file could not be created for any reason.

Getting file information

Several of the methods of the File class simply return information about a file or directory. You can find out whether the File object represents a file or directory, for example, by calling its isDirectory or isFile method. Other methods let you find out whether a file is read-only or hidden, or retrieve the file’s age and the time when it was last modified.

To get just the filename without the path, use the getName method:

File f = new File(“C:\MyFolder\MyFile.txt”);

String name = f.getName;

This sets the name variable to MyFile.txt.

To get the full path for a file (the path plus the filename), use the getCannonicalPath method:

File f = new File(“C:\MyFolder\MyFile.txt”);

String name = f.getCannonicalPath;

This sets the name variable to C:MyFolderMyFile.txt.

Getting directory contents

A directory is a file that contains a list of other files or directories. You can tell whether a particular File object is a directory by calling its isDirectory method. If the file is a directory, you can get an array of all the files contained in the directory by calling the listFiles method.

Here’s an example that prints the name of every file in a directory:

private void ShowFiles(String path)

{

File dir = new File(path);

if (dir.isDirectory())

{

File[] files = dir.listFiles();

for (File f : files)

System.out.println(f.getName());

}

}

Here’s a version that lists only files, not subdirectories, and doesn’t list hidden files:

private void ShowFiles(String path)

{

File dir = new File(path);

if (dir.isDirectory())

{

File[] files = dir.listFiles();

for (File f : files)

{

if (f.isFile() && !f.isHidden())

System.out.println(f.getName());

}

}

}

tip.eps Directory listings are especially well suited to recursive programming, because each File object returned by the listFiles method may be another directory that itself has a list of files and directories. For an explanation of recursive programming, see Recursion in Part 2.

Renaming files

You can rename a file by using the renameTo method. This method uses another File object as a parameter that specifies the file you want to rename the current file to. It returns a Boolean value that indicates whether the file was renamed successfully.

The following statements change the name of a file named myfile.txt to yourfile.txt:

File f = new File(“myfile.txt”);

if (f.renameTo(new File(“yourfile.txt”)))

System.out.println(“File renamed.”);

else

System.out.println(“File not renamed.”);

Depending on the capabilities of the operating system, the renameTo method can also move a file from one directory to another. This code moves the file myfile.txt from the folder c:mydirectory to the folder c:yourdirectory:

File f = new File(“c:\mydirectorymyfile.txt”);

if (f.renameTo(

new File(“yourdirectory\myfile.log”)))

System.out.println(“File moved.”);

else

System.out.println(“File not moved.”);

tip.eps Always test the return value of the renameTo method to make sure that the file was renamed successfully.

Deleting a file

To delete a file, create a File object for the file and then call the delete method, as in this example:

File f = new File(“myfile.txt”);

if (f.delete())

System.out.println(“File deleted.”);

else

System.out.println(“File not deleted.”);

If the file is a directory, the directory must be empty to be deleted.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset