The FileOutputStream class is used to perform simple file output operations. It is used to write binary data to a file. The FileOutputStream class can be instantiated by using any of the following constructors:
- FileOutputStream(String name): This constructor creates a connection to write to the file with the name specified in the argument. It throws a FileNotFoundException if the file does not exist or cannot be opened for some reason.
- FileOutputStream(String name, boolean append): This constructor creates a connection to write to the file with the name specified in the argument. If the second argument of the constructor is true, the bytes are written to the end of the file rather than to the beginning of the file. It throws a FileNotFoundException if the file does not exist or cannot be opened for some reason.
- FileOutputStream(File file):This constructor creates an OutputStream and establishes a connection with the actual file. It throws a FileNotFoundException if the file does not exist or cannot be opened for some reason.
- FileOutputStream(File file, boolean append): This constructor creates an OutputStream and establishes a connection with the actual file. If the second argument of the constructor is true, the bytes are written to the end of the file rather than to the beginning of the file. It throws a FileNotFoundException if the file does not exist or cannot be opened for some reason.
- FileOutputStream(FileDescriptor fd Object):
This constructor uses a file descriptor object to write to a specified file. The file descriptor object represents a connection with the existing file.
The following code illustrates how to use the file output strem class:
import java.io.*;
class Forest {
Forest () {System.out.println (“1″); }
}
public class Tree extends Forest implements Serializable {
Tree () { System.out.println(“2″);}
public static void main(String [] args) {
Tree t = new Tree ();
try {
FileOutputStream fos = new FileOutputStream (“forest.txt”);
ObjectOutputStream os = new ObjectOutputStream (fos );
os.writeObject (t);
os.close ();
FileInputStream fis = new FileInputStream(“forest.txt”);
ObjectInputStream is = new ObjectInputStream (fis);
Tree t1 = (Tree) is.readObject ();
is.close ();
} catch (Exception ex) {}
}
}
Responses to “What is the FileOutputStream class?”