FileOutputStream in Java.

Java 8Object Oriented ProgrammingProgramming

This writes data into a specific file or, a file descriptor (byte by byte). It is usually used to write the contents of a file with raw bytes, such as images.

To write the contents of a file using this class −

  • First of all, you need to instantiate this class by passing a string variable or a File object, representing the path of the file to be read.

FileOutputStream outputStream = new FileOutputStream("file_path");
File file = new File("file_path"); FileOutputStream outputStream = new FileOutputStream (file);

You can also instantiate a FileOutputStream class by passing a FileDescriptor object.

FileDescriptor descriptor = new FileDescriptor(); FileOutputStream outputStream = new FileOutputStream(descriptor);
  • Then write the data to a specified file using either of the variants of write() method −

    • int write(int b) − This method accepts a single byte and writes it to the current OutputStream.

    • int write(byte[] b) − This method accepts a byte array as a parameter and writes data from it to the current OutputStream.

    • int write(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and writes its contents to the current OutputStream.


Assume we have the following image in the directory D:/images

Following program reads the contents of the above image and writes it back to another file using the FileOutputStream class.

public class FileInputStreamExample {
   public static void main(String args[]) throws IOException {
      //Creating a File object
      File file = new File("D:/images/javafx.jpg");
      //Creating a FileInputStream object
      FileInputStream inputStream = new FileInputStream(file);
      //Creating a byte array
      byte bytes[] = new byte[(int) file.length()];
      //Reading data into the byte array
      int numOfBytes =;
      System.out.println("Data copied successfully...");
      //Creating a FileInputStream object
      FileOutputStream outputStream = new FileOutputStream("D:/images/output.jpg");
      //Writing the contents of the Output Stream to a file
      System.out.println("Data written successfully...");


Data copied successfully...
Data written successfully...

If you verify the given path you can observe the generated image as −

Published on 12-Sep-2019 06:42:20