Next: The FileInputStream class. Up: Files. Previous: The File class.


The FileOutputStream class

Textbook: Section 14.3

A FileOutputStream object represents a file into which you can write bytes. It's for writing raw bytes - we'll get into more sophisticated objects for writing characters or writing more complex items later.

Constructors

When you create a FileOutputStream object, the file is opened for writing. The file is set up so that the first write occurs at the first byte of the file - thus, effectively, when you create a FileOutputStream object, the file it represents is immediately cleared.

FileOutputStream(File file) throws FileNotFoundException
Creates a FileOutputStream object for the specified file. (It throws FileNotFoundException if the specified file isn't writeable.)
Notice that this method throws an exception. This means that whenever you try to create a FileOutputStream object, you'll have to deal with the possibility that it raises an exception. Exceptions become a huge pain when you begin to deal with files, since so many things can go wrong.

A FileNotFoundException is an inappropriate name for what this method does, since if the file doesn't exist, it goes ahead and creates one. This exception is raised when creating the file is impossible - for example, if the file exists, but you don't have write permission for it. Or if it doesn't exist, and you don't have permission to create a new file in the directory.

Writing methods

As you write into the file, the FileOutputStream object tracks where you currently are in the file. This is called the file pointer.

void write(byte[] b) throws IOException
Writes the bytes of b into the file just after the location where it last wrote.
void write(byte[] b, int offs, int num) throws IOException
Writes num bytes from b, beginning at index offs in the array, into the file just after the location where it last wrote.
void close() throws IOException
Closes the file, ensuring that everything is saved on the disk and making the object ineligible for use in further writes.
It's important that you close the file once you're done. This is because the program may try to buffer data in memory - trying to conserve the number of times it writes to disk, since disks are so slow. If you don't close the file, and the program doesn't finish properly, then it may run into a situation where the buffer is lost.

Additionally, operating systems typically restrict each program on how many files they can have open at once. So if you don't close it, but your program tries to open several files later on, you may find that on the 64th file the program is suddenly no longer saving.


Next: The FileInputStream class. Up: Files. Previous: The File class.