CREATING FILE OBJECTS USING File

advertisement
CREATING FILE OBJECTS USING
THE File CLASS
The File class is part of the java.io package and is used for creating a file object. By creating a File
object, we can create programs that create new files, check if a file(s) exists, delete a file(s), read
contents from a file, etc.
CONSTRUCTORS
The following is a list of some of the constructors and methods included in the File class:
CONSTRUCTOR
DESCRIPTION
File(String pathName)
Creates a file with the specified path name.
METHODS
The following table outlines some of the methods included in the File class:
METHODS
DESCRIPTION
boolean canRead()
Determines whether the file can be read.
boolean canWrite()
Determines whether data can be written to the file.
boolean createNewFile()
Creates the file on disk if it doesn’t already exist. Returns true if the
file was created; false if the file already existed. Throws
IOException.
boolean delete()
Deletes the file. Returns true if the file was successfully deleted.
boolean exists()
Checks if the file exists.
String getCanonicalPath()
Returns the complete path to the file. Throws IOException.
String getName()
Returns the name of the file.
boolean renameTo(File f)
Renames the File object to the specified destination File object.
Returns true if the renaming was successful.
The File Class
Page 1 of 4
CREATING A FILE
The following program will create a new file called data.txt in the H:\My Documents directory:
import java.io.*;
public class FileClassExample {
public static void main(String[] args) throws IOException {
// Declare and initialize File object
File textFile = new File(“H:\\My Documents\\data.txt”);
textFile.createNewFile();
}
}
EXCEPTION HANDLING
A program will often run into problems as it is running. For example, in the above program, the file does
not get written into the C: directory because we have been restricted from writing files to the local
directory on the school computers. This is just one example of an error that affects the execution of a
program. There are a number of other causes for errors – e.g. a program may not be able to read data
from a file, a file might not exist, etc. It is the responsibility of a good programmer to handle such
errors, or exceptions, in order to prevent a program from unexpectedly terminating or failing to
complete its required tasks.
Whenever you use a statement or a method that might throw an exception – such as the
createNewFile() method that we used in the above example – you should write an exception
handler that performs an action when an exception occurs. A try-catch-finally statement is used to
write an exception handler, and it takes the following form:
try
{
statements that can throw exceptions
}
catch (exception error)
{
statements executed when exception is thrown
}
finally
{
statements executed whether or not exceptions occur
}
The File Class
Page 2 of 4
Let’s rewrite our FileClassExample program using an exception handler:
import java.io.*;
public class FileClassExample {
public static void main(String[] args) {
File textFile = new File(“H:\\My Documents\\data.txt”);
try
{
textFile.createNewFile();
}
catch(IOException e)
{
System.out.println(“File could not be created!”);
System.err.println(“IOException: ” + e.getMessage());
}
}
}
Our new program will still not be able to write the file, but it’s going to do a little more than just not
work. This time the program will generate a message and advise the user the cause of the error. The
getMessage() method is part of the Throwable class which returns a String containing information
about the exception. In this example, the error message that is generated and outputted to the user is
“Access is denied”. The err stream is used for outputting error messages to the user.
RENAMING FILES
You can rename a file by using the renameTo() method, which uses another File object as a parameter
that specifies the file you want to rename the current file to. Like the createNewFile() method, it also
returns a boolean value indicating whether or not the file was successfully renamed. The following
example, renames a file called test.txt to quiz.txt:
File textFile = new File(“H:\\My Documents\\test.txt”);
if (textFile.renameTo(new File(“H:\\My Documents\\quiz.txt”)))
{
JOptionPane.showMessageDialog(null, “File renamed!”, “”,
JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, “File not renamed!”,
“Error”, JOptionPane.ERROR_MESSAGE);
}
The File Class
Page 3 of 4
DELETING A FILE
We can also delete a file by using the delete() method as follows:
File textFile = new File(“H:\\My Documents\\quiz.txt”);
if (textFile.delete())
{
JOptionPane.showMessageDialog(null, “File deleted!”, “”,
JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, “File not deleted!”,
“Error”, JOptionPane.ERROR_MESSAGE);
}
The File Class
Page 4 of 4
Download