Thursday, 19 August 2021

FileOutputStream class in Java

 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 FileOutputStream.



OutputStream Hierarchy

Java output stream hierarchy


FileOutputStream class declaration

  1. public class FileOutputStream extends OutputStream  

FileOutputStream class methods

MethodDescription
protected void finalize()It is used 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
  1. import java.io.FileOutputStream;  
  2. public class FileOutputStreamExample {  
  3.     public static void main(String args[]){    
  4.            try{    
  5.              FileOutputStream fout=new FileOutputStream("D:\\test.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 test.txt is set with the data A.

test.txt

A

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:\\test.txt");    
  6.              String s="Welcome to javawindow.";    
  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 test.txt is set with the data Welcome to javaWindow.

test.txt

Welcome to javaWindow.

No comments:

Post a Comment

Please share your feedback