ptg7068951
Streams 285
. length()—The size of the file, as a longvalue
. createNewFile()—Creates a file of the same name, if one does not
exist already
. delete()—Deletes the file, if it exists
. renameTo(File)—Renames the file, using the name of the File
object specified as an argument
You also can use a Fileobject to represent a folder on your system rather
than a file. Specify the folder name in the Fileconstructor, which can be
absolute (such as “C:\MyDocuments\”) or relative (such as “java\
database”).
After you have an object representing a folder, you can call its listFiles()
method to see what’s inside the folder. This method returns an array of
Fileobjects representing every file and subfolder it contains.
Reading Data from a Stream
The first project of the hour is to read data from a file using an input
stream. You can do this using the FileInputStreamclass, which represents
input streams that are read as bytes from a file.
You can create a file input stream by specifying a filename or a Fileobject
as the argument to the FileInputStream()constructor method.
The file must exist before the file input stream is created. If it doesn’t, an
IOExceptionis generated when you try to create the stream. Many of the
methods associated with reading and writing files generate this exception,
so it’s often convenient to put all statements involving the file in their own
try-catchblock, as in this example:
try {
File cookie = new File(“cookie.web”);
FileInputStream stream = new FileInputStream(cookie);
System.out.println(“Length of file: “+ cookie.length());
} catch(IOException e) {
System.out.println(“Could not read file.”);
}
File input streams read data in bytes. You can read a single byte by calling
the stream’s read()method without an argument. If no more bytes are
available in the stream because you have reached the end of the file, a byte
value of –1 is returned.