| . Is part of the java.io package |
| |
| . Is an extension of the OutputStream class, an
abstract class that describes the behavior of an output stream |
| |
|
| |
| . Is a low-level class that can be used to send
individual, 8-bit bytes to a stream |
| |
| . Has several constructors. The most frequently used constructs
a FileOutputStream object from a File object that encapsulates the
file's pathname. For example, if fd is the reference of a File object |
| |
| |
| FileOutputStream out = new FileOutputStream(fd); |
| It will construct a FileOutputStream object
for sending bytes to the file. If the file already
exists, its contents will be replaced (there is an
overloaded constructor to specify appending). Because
a checked, IOException may occur, the statement should
be enclosed in a try block with an appropriate catch. |
| |
| . Has a few useful methods. The two most used are: |
| |
|
| |
| Because a checked, IOException may occur, calls to
these methods should be enclosed in a try block with an
appropriate catch. Consult the Java API documentation for more details. |
| |
| |
| . Example. The following program can
be used to create a file of numbers on disk. |
| // Open an output stream for the file. |
| out = new FileOutputStream(fd); |
| |
| // This loop asks the user to enter a import |
| |
java.io.*;
public class AppFOS
{
public static void main(String[] args)
{
// Local variables and object references.
char again = 'y';
File fd;
FileOutputStream out;
// Get the path name from the user.
System.out.print("Enter the file's complete path name: ");
fd = new File(Keyboard.readString());
// Try to write data to the output stream.
try
{
//number and writes it to the
// stream. The user is then asked if they want to enter another.
while (again == 'Y' || again == 'y')
{
System.out.print("Enter a number: ");
int theNumber = Keyboard.readInt();
out.write(theNumber);
System.out.print("Again? (Y/N): ");
again = Keyboard.readChar();
}
// Close the stream.
out.close();
System.out.println("Closed - " + fd.getPath());
}
// Catch an IOException if one is thrown.
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
} |