FileOutputStream

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java FileOutputStream Class

Java FileOutputStream is an output stream used for writing data to a file.

If you have to write primitive values into a file, use FileOutputStream class. You can write byte-oriented as well as character-oriented data through FileOutputStream class. But, for character-oriented data, it is preferred to use FileWriter than FileOutStream.

FileOutputStream class declaration

Let's see the declaration for Java.io.FileOutputStream class:

  1. public class FileOutputStream extends OutputStream  

FileOutputStream class methods

Method

Description

protected void finalize()

It is sued to clean up the connection with the file output stream.

void write(byte[] ary)

It is used to write ary.length bytes from the byte array to the file output stream.

void write(byte[] ary, int off, int len)

It is used to write len bytes from the byte array starting at offset off to the file output stream.

void write(int b)

It is used to write the specified byte to the file output stream.

FileChannel getChannel()

It is used to return the file channel object associated with the file output stream.

FileDescriptor getFD()

It is used to return the file descriptor associated with the stream.

void close()

It is used to closes the file output stream.

 

Java FileOutputStream Example 1: write byte

The content of a text file testout.txt is set with the data A.

  1. import java.io.FileOutputStream;  
  2. public class FileOutputStreamExample {  
  3.     public static void main(String args[]){    
  4.            try{    
  5.              FileOutputStream fout=new FileOutputStream("D:\testout.txt");    
  6.              fout.write(65);    
  7.              fout.close();    
  8.              System.out.println("success...");    
  9.             }catch(Exception e){System.out.println(e);}    
  10.       }    
  11. }  

Output:

Success...

The content of a text file testout.txt is set with the data A.

testout.txt

A

testout.txt

Java FileOutputStream example 2: write string

  1. import java.io.FileOutputStream;  
  2. public class FileOutputStreamExample {  
  3.     public static void main(String args[]){    
  4.            try{    
  5.              FileOutputStream fout=new FileOutputStream("D:\testout.txt");    
  6.              String s="Welcome to javaTpoint.";    
  7.              byte b[]=s.getBytes();//converting string into byte array    
  8.              fout.write(b);    
  9.              fout.close();    
  10.              System.out.println("success...");    
  11.             }catch(Exception e){System.out.println(e);}    
  12.       }    
  13. }  

Output:

Success...

The content of a text file testout.txt is set with the data Welcome to javaTpoint.

testout.txt