FileOutputStream in Java | Methods, Example

A FileOutputStream in Java is a concrete subclass of OutputStream that provides methods for writing data to a file or to a FileDescriptor.

In simple words, a file output stream is an OutputStream that writes data to a file. It stores data in the form of individual bytes.

A file output stream can be used to create a text file. For example, if you want to write strings into a text file, use FileOutputStream object.

We can write both byte-oriented as well as character-oriented data via FileOutputStream class. But, for character-oriented data, it is recommended to use FileWriter than FileOutputStream.

FileOutputStream was added in Java 1.0 version. It is present in the java.io.FileOutputStream package.

FileOutputStream Class declaration in Java


FileOutputStream class is derived from OutputStream class. Output stream class is an abstract superclass of all classes representing an output stream of bytes like FileOutputStream, ObjectOutputStream, etc.

Java FileOutputStream class implements Closeable, Flushable, and AutoCloseable interfaces.

The general declaration of java.io.FileOutputStream class in java is as follows:

public class FileOutputStream
    extends OutputStream
     implements Closeable, Flushable, AutoCloseable

 Constructor of FileOutputStream class


To create a FileOutputStream instance, FileOutputStream class defines the following constructors. They are as follows:

1. FileOutputStream(File file): This form of constructor creates a file output stream to write data to the specified File object. The contents of any existing file will be overwritten.

2. FileOutputStream(File file, boolean append): This constructor creates a file output stream to write data to the specified File object. If append is true, data are appended to the existing file with the following existing contents.

If append is false, existing data in the file will be cleared when the file output stream is constructed.

3. FileOutputStream(FileDescriptor fdObj): This constructor creates a file output stream for writing data to the specified file descriptor.

4. FileOutputStream(String filename): This form of constructor creates a file output stream to write to the file with the specified filename.

5. FileOutputStream(String name, boolean append): This constructor creates a file output stream to write to the file with the specified name.

If append is true, data will be appended to the file with the following existing contents. If append is false, the contents of the existing file will be overwritten.

In all the above cases, if the file is not opening for writing for any reason, an exception named FileNotFoundException will be thrown.

How to Create File using FileOutputStream?


There are the following steps to create a text file that will store some characters or text. They are:


1. First, we need to read data from the keyboard. For this purpose, we will have to attach keyboard to an input stream class. The syntax for reading data from keyboard is given below:

DataInputStream dis = new DataInputStream(System.in);

In the above statement, System.in represents the keyboard that is linked with DataInputStream object whose reference variable is dis.

2. Second, attach a file where data is to be stored to an output stream. For this purpose, the syntax for attaching a file fileout.txt to FileOutputStream is given below:

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

Here, for represents object reference variable of FileOutputStream class.

3. Third step is to read data from DataInputStream and write it into FileOutputStream. This means that we will read data from dis object and write it into fos object. The syntax is as follows:

ch = (char)dis.read(); // Read a single character into ch.
  fos.write(ch); // write ch into file.

At last, file must be closed after performing input or output operations on it. Otherwise, data on the file may be corrupted. Look at the below figure to understand all these steps.

Steps to create a text file using FileOutputStream in Java

FileOutputStream Class Methods in Java


FileOutputStream class does not define any new methods. Since FileOutputStream class is derived from OutputStream class, therefore, all the methods in this class are inherited from OutputStream.


The most common useful methods are as follows:

1. void close(): This method is used to close the file output stream and releases any system resources associated with this stream.

2. protected void finalize(): This method cleans up the connection with the file output stream.

3. FileChannel getChannel(): This method returns the unique FileChannel object associated with the file output stream.

4. FileDescriptor getFD(): It returns the file descriptor associated with the stream.


5. void write(int b): This method writes the specified or single byte to this file output stream.

6. void write(byte[ ] b): It writes a complete array of bytes to the file output stream.

7. void write(byte[ ] b, int off, int numBytes): This method writes numBytes bytes from the specified byte array starting at offset off to the file output stream.

8. void flush( ): This method flushes the output stream and forces any buffered output bytes to be written out.

All these methods will throw an exception named IOException if any I/O error occurs. So, you must declare to throw java.io.IOException in the method or place the code in a try-catch block.

Example Program based on Java FileOutputStream


1. Let’s take an example program where we will write a single byte into a file.

Program source code 1:

package javaProgram;
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String[] args)
{
try { 
// Store the filepath into the variable filepath of type String.
     String filepath = "D:\\fileout.txt";

// Create an object of FileOutputStream class to attach file with FileOutputStream and pass the filepath to its constructor.	 
    FileOutputStream fos = new FileOutputStream(filepath);    
    fos.write(87);    
    fos.close(); // Closing file.    
 
     System.out.println("Successfully written");    
 }catch(FileNotFoundException e){
      System.out.println(e);
  }    
 }
}
Output:
      Successfully written

Data “W” is successfully written into the text file fileout.txt.

2. Let’s take another example program to write a string into the text file. Look at the source code.

Program source code 2:

package javaProgram;
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String[] args)
{
try { 
 String filepath = "D:\\fileout.txt";	 
 FileOutputStream fos = new FileOutputStream(filepath);
 String str = "Welcome to Scientech Easy, Shivam complex, Dhanbad"; 
   
 byte bytearray[ ] = str.getBytes(); // Converting string into byte array.
  fos.write(bytearray);    
  fos.close();    
 
  System.out.println("Successfully written");    
 }catch(Exception e){
    System.out.println(e);
  }    
 }
}
Output:
      Successfully written

Data “Welcome to Scientech Easy, Shivam complex, Dhanbad” is successfully written into the text file fileout.txt.

3. Let’s take an example program where we will understand how to read data from the keyboard and write it to fileout.txt file. Look at the program source code to understand better.

Program source code 3:

package javaProgram;
import java.io.DataInputStream;
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String[] args)
{
try { 
// Create an object of DataInputStream to attach keyboard to DataInputStream.
   DataInputStream dis = new DataInputStream(System.in); 	 
   	
// Store the filepath into the variable filepath of type String.   
   String filepath = "D:\\myfileout.txt";

// Create an object of FileOutputStream to attach myfileout file to FileOutputStream.   
   FileOutputStream fos = new FileOutputStream(filepath); 
   System.out.println("Enter the text (@ at the end)");
   
    int value = 0;
// Read the values (in byte form) from dis into ch and write them into fos.    
   while((value = dis.read()) != '@'){
   char ch = (char)value; // Converting byte values into characters. 
   fos.write(ch);  
  }

  fos.close(); // Closing file.   
  System.out.println("Successfully written...");    
 }catch(Exception e){
   System.out.println(e);
 }    
 }
}
Output:
       Enter the text
       Welcome to Scientech Easy, Dhanbad
       Best Online Portal to become expert in Java coding
       @
       Successfully written...

Data “Welcome to Scientech Easy, Dhanbad, Best Online Portal to become expert in Java coding” has been successfully written in the text file “myfileout”.

In this example program, we read the data from the keyboard and write them into myfileout.txt file. This program takes data from the keyboard as long as the user types @ to end the statement.

You can observe the output, we have entered two lines of statements and typed @ to end the statement. Now, open your myfileout.txt file and see that data is successfully written into the file or not.

If the above program is executed again, you will notice that the old data of myfileout.txt file has been lost completely and recent data will be stored in the file when you will write the text. Look at the output of the second execution of the program.

Output:
      Enter the text (@ at the end)
      Industrial Java Programming by Scientech Easy
      @
      Successfully written...

Notice that the previous two lines of statements have been deleted from the file and the file has been created as a fresh file. The fresh file myfileout.txt has now stored only the third line that has been entered in the last execution of code.

If you do not want to lose previous data of the file and just want to append the new data at the end of already existing data, you open the file by writing true along with filename. The syntax is as follows:

FileOutputStream fos = new FileOutputStream(filepath, true);

When you will use this statement in the previous program, execute the program several times, still all the previous data will be preserved and new data will be added to the old data.

How to Copy Data from one File to another File?


Let’s create a program to copy data from one file to another file using FileInputStream and FileOutputStream classes. In the first file myfile.txt, we will store data as “Welcome to Scientech Easy”.

Then, we will copy it and store it in the second file myfileout.txt. Look at the source code to understand better.

Program source code 4:

package javaProgram;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class CopyData {
public static void main(String[] args)
{
 try
 {    
  FileInputStream fis = new FileInputStream("D:\\myfile.txt");
  FileOutputStream fos = new FileOutputStream("D:\\myfileout.txt");
        
 int i = 0;
 while ((i = fis.read()) != -1){
  char ch = (char)i;
   fos.write(ch);
  }     
  fis.close();    
  System.out.println("Successfully written...");    
}catch(Exception e)
 {
   System.out.println(e);
 }
 }
}
Output:
       Successfully written...

The data of file myfile.txt is copied in the file fileout.txt. Now open the fileout.txt file and verify that data is successfully copied or not.


Hope that this tutorial has covered all the important points concerning FileOutputStream class in Java with example programs. I hope that you will have understood all programs and practiced them.
Thanks for reading!!!
Next ⇒ BufferedInputStream in Java

⇐ Prev Next ⇒