FileOutputStream class

 

††††††††††††††††† See OutputStream classfor descriptions of the methods FileOutputStream can use.They are:

 

write( int b )††††††††††††††††††††††††††† Writes a single byte, supplied as the low-order byte in an int.

write( byte[ ] )†††††††††††††††††††††††† Writes an array of bytes.

write( byte[ ], offset, len )††††††† Writes a portion len of a byte array, beginning at offset

close( ) ††††††††††††††††††††††††††††††††††† Closes the stream, flushing it first.

flush( ) ††††††††††††††††††††††††††††††††††† Flushes all associated buffers in a stream without closing it.

 

plus it adds:

 

.finalize( )†††††††††††††††††††††††††††††† Ensures a close( ).

.getChannel( )†††††††††††††††††††††††† Returns the FileChannel object.These arenít discussed here.

.getFD( )†† ††††††††††††††††††††††††††††††† Returns the file descriptor.

 

FileOutputStream is meant for writing streams of raw bytes to files. For writing streams of human-readable characters, you should consider using the Writer class FileWriter.

 

FileOutputStream will create a file if that file does not exist. If it exists it will overwrite it. i.e.

 

File f = new File( "some_filename");
FileOutputStream fos = new FileOutputStream ( f);
or, the same thing:
FileOutputStream fos = new FileOutputStream ( "some_filename");

 

 You can append to the ends of files with FileOutputStream, instead of overwriting them.It has two constructors with a second boolean argument where true means to append.
 
File f = new File( "some_filename");
FileOutputStream fos = new FileOutputStream ( f, true );
or
FileOutputStream fos = new FileOutputStream ( " some_filename ", true );

 

The following snippet uses FileOutputStream to copy a file by rewriting it a byte at a time, without buffering.

 

import java.util.*;
 
try {
††† FileInputStream fis = new FileInputStream( "input_filename" );
††† FileOutputStream fis = new FileOutputStream( "output_filename" );
††† int x;
††† while ( (x = fis.read( ) ) != -1 ) {
††††††† fos.write( x );
††† }
††† fis.close( );
††† fos.close( );
} 
catch (IOException e) { }
 

FileOuputStream is usually chained to other output stream classes, most notably BufferedOutputStream to provide buffering. i.e. The example above is repeated with output buffering.BufferedOutputStream's methods are used.

 

import java.util.*;
 
try {
††† FileInputStream fis = new FileInputStream( "input_filename" );
††† BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream( "output_filename" );
††† int x;
††† while ( (x = fis.read( ) ) != -1 ) {
††††††† bos.write( x );
††† }
††† fis.close( );
††† bos.close( );
} 
catch (IOException e) { }