Open In App

FileOutputStream in Java

Last Updated : 29 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The FileOutputStream class in Java is used to write raw bytes to a file. It is part of the java.io package and is mainly used for writing binary data (like images, audio, PDFs, etc.) but can also handle text (though FileWriter is usually preferred for text).

Example: Here, the below Java Program demonstrates how to use FileOutputStream to write data to a file in Java.

Java
import java.io.*;

class Geeks {
    public static void main(String[] args)
    {
        String data = "Hello, World!";

        try (FileOutputStream fos = new FileOutputStream("output.txt")) {
                 
            // Convert the string into bytes
            byte[] dataBytes = data.getBytes();

            // Write the bytes to the file
            fos.write(dataBytes);

            System.out.println("Data successfully written to the file.");
        }
        catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}

Output
Data successfully written to the file.

What is meant by storing data in Java files

file
Data Flow from RAM to Hard Disk using FileOutputStream

This image shows how FileOutputStream works in Java. Data stored in RAM (variables) is sent to an output stream object, which transfers the data to a file. Finally, the file is saved on the hard disk, making the data persistent.

Hierarchy of FileOutputStream

autocloseable
Hierarchy of FileOutputStream

Declaration of FileOutputStream

public class FileOutputStream extends OutputStream

Note:

  • FileOutputStream is a subclass of OutputStream.
  • It implements the Closeable and Flushable interfaces.

Constructors of FileOutputStream

1. FileOutputStream( String name):

Creates an object of file output stream to write to the file with the particular name mentioned.

Example:

FileOutputStream fos = new FileOutputStream( "output.txt");

2. FileOutputStream(File file):

Creates a file output stream to write to the file represented by the specified File object. The file is overwritten if it already exists.

Example:

File f = new File("output.txt");

FileOutputStream fos = new FileOutputStream(fi);

3. FileOutputStream( File file, boolean append):

Creates a file output stream object represented by specified file object. Appends data to the file if append is true

Example:

File f = new File("output.txt");

FileOutputStream fos = new FileOutputStream(fi, true);

4. FileOutputStream( String name, boolean append):

Creates an object of file output stream to write to the file with the specified name. If append is true, data is appended to the file instead of overwriting it.

Example:

FileOutputStream fos = new FileOutputStream("output.txt", true);

5. FileOutputStream(FileDescripter fdobj):

Creates a file output stream for writing to the specified file descriptor, which represents an existing connection with the actual file in the file system.

Example:

FileOutputStream fout = new FileOutputStream(FileDescripter fdobj);

Steps to Write Data to a File using FileOutputStream

Step 1: Attach a File Path to FileOutputStream

First, attach a file path to a FileOutputStream as shown below:

FileOutputStream f = new FileOutputStream(“file1.txt”);

Step 2: Write data to the file

Use the write() method of FileOutputStream to write data.

f.write(data.getBytes());

Step 3: Close the stream

Use close() to close the stream after you are done doing writing.

f.close()

Example: The below Java Program demonstrates the basic file handling in Java using the FileOuputStreram class.

Java
import java.io.*;

public class Geeks {
    public static void main(String[] args) {

        String s = System.getProperty("user.dir");

        // Print the current directory
        System.out.println("Current working directory: " + s);

        // Use try-with-resources to ensure the stream is closed automatically
        try (FileOutputStream fout = new FileOutputStream("name3.txt", false)) { 

            // String to be written to the file
            String st = "TATA";

            // Convert the string to a byte array and write it directly
            fout.write(st.getBytes());

        } catch (IOException e) {
            
            // Handle exceptions if file operations fail
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}

Explaination:

  • This code writes the String "TATA" to a file names as name3.txt.
  • The file will be created or overwritten in the current working directory.
  • The file name3.txt will be located in the directory from which the program is executed.
  • The FileOutputStream is opened in overwrite mode (with false), meaning any existing content in name3.txt will be deleted and only "TATA" will be written to the file.
  • The try-with-resources block ensures that the file stream is properly closed after the writing operation
  • The string "TATA" is converted into a byte array using st.getBytes() and written to the file directly.
  • If name3.txt does not exist, it will be created in the current working directory.
  • If name3.txt already exists, its content will be replaced with "TATA".

The data i.e. the string TATA will be transferred to file.

Before running the program:

BeforeRunning
Before running program

After running the program:

name3.txt file is created and the text "TATA" is saved in the file.

AfterRunning
after running program

Output:

Output
Output

Some Important FileOutputStream Methods

1. Write()

  • write(): this writes the single byte to the file output stream.
  • write(byte[] array): this writes the specified array's bytes to the output stream.
  • write(byte[] array, int start, int length): this writes the number of bytes equal to length to the output stream from an array starting from the position start.

Example: This example demonstrates how to write a string to a file using FileOutputStream in Java

Java
import java.io.FileOutputStream;
import java.util.*;

public class Geeks {
    public static void main(String[] args)
    {

        String data = "Welcome to GfG";

        try {
            FileOutputStream output = new FileOutputStream("output.txt");

            // The getBytes() method used converts a string into bytes array.
            byte[] array = data.getBytes();

            // writing the string to the file by writing each character one by one Writes byte to the file
            output.write(array);

            output.close();
        }

        catch (Exception e) {
            e.getStackTrace();
        }
    }
}

When we run the program, the "Welcome to GfG" line is copied to output.txt file.

2. flush()

For clearing the OutputStream, we use the flush() method. This method forces all the data to get stored to its destination.

Example: This example demonstrates how to write a string to a file and explicitly flush the output stream using flush() method

Java
import java.io.FileOutputStream;
import java.io.IOException;

public class Geeks {
    public static void main(String[] args)
        throws IOException
    {

        FileOutputStream out = null;
        String data = "Welcome to GfG";

        try {
            out = new FileOutputStream(" flush.txt");

            // Using write() method
            out.write(data.getBytes());

            // Using the flush() method
            out.flush();
            out.close();
        }
        catch (Exception e) {
            e.getStackTrace();
        }
    }
}

If, we run the program, the file flush.txt is filled with the text of the string"Welcome to GfG"

3. close() method

This method closes the file OutputStream. Once it is called, we cannot use other methods. 

Example: This example demonstrates that attempting to write to a FileOutputStream after closing it results in an IOException

Java
import java.io.FileOutputStream;
import java.io.IOException;

public class Geeks {
    public static void main(String[] args)
    {
        FileOutputStream out = null;
        String data = "Welcome to GfG";

        try {
            out = new FileOutputStream("example.txt");

            // Writing data to the file
            out.write(data.getBytes());

            // Closing the output stream
            out.close();

            // Trying to write again after closing the stream This will throw an IOException
            out.write("This will cause an error".getBytes()); 

        } catch (IOException e) {
            
            // Exception is thrown when attempting to write after closing the stream
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output
Error: Stream Closed

Methods of fileOutputStream

MethodDescription
void close() It closes the file output stream.
protected void finalize()It is used to clean up all the connection with the file output stream and finalize the data.
FileChannel getChannel() Returns the unique FileChannel object associated with this file output stream.
FileDescriptor getFD() It returns the file descriptor associated with the stream.
void write(int b)It is used to write the specified byte to the file output stream.
void write(byte[] arr)It is used to write data in bytes of arr[] to file output stream.
void write(byte[] ary, int off, int len)It is used to write the number of bytes equal to length to the output stream from an array starting from the position start.

Methods inherited from OutputStream

MethodDescription
flush()this method forces to write all data present in the output stream to the destination(hard disk).
nullOutputStream()this method returns a new OutputStream which discards all bytes. The stream returned is initially open.

Article Tags :
Practice Tags :

Explore