FileOutputStream in Java

The FileOutputStream class is used to write data, byte by byte to a file. The FileOutputStream is derived from abstract class OutputStream.  It can throw FileNotFoundException or SecurityException. We need to remember that creation of FileOutputStream is not dependent on the file that already exists. In fact FileOutStream will create the file before opening it for output. If we attempt to open a read only file the throw an IOException. The return type of FileOutputStream is void.

Example:

//From fileOutputStreamExample.java

import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 *
 * @author JavaHotSpot
 */

public class fileOutputStreamExample
{
  public static void main(String args[])
  {
      try
      {
        String s1= "This is example of fileoutputstream class";
        byte[] data=s1.getBytes();  // Converts string into bytes
        byte[] indata=new byte[1000];
        int n=data.length;
        int size;
        System.out.println("Writing data, byte by byte...");
        FileOutputStream fo=new FileOutputStream("C:\\file1.txt");
        for(int i=0;i<n;i++)
        {
            fo.write(data[i]);
        }
        System.out.println("Writing is Done...!");
        fo.close();
        System.out.println("Reading....");
        FileInputStream fi=new FileInputStream("C:\\file1.txt");
        size=fi.available();
        fi.read(indata);
        System.out.println("File Content is =\n"+new String(indata,0,size));
        fi.close();

      }
      catch(Exception ex)
      {
          System.err.println(ex);
      }
  }
}


Output:
Writing data, byte by byte...
Writing is Done...!
Reading....
File Content is =
This is example of fileoutputstream class