Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
The need to store data in Files
3.
FileOutputStream
4.
Constructors
5.
Methods/Functions
6.
Example
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024

The FileOutputStream Class

Author Yashesvinee V
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

A file output stream writes data to a File or FileDescriptor. The underlying platform decides if a new file needs to be created or an existing one is to be updated. FileOutputStream writes streams of raw bytes such as primitive values or image data. A FileWriter is used to write streams of characters. Some platforms may allow a file to be opened for writing by only one FileOutputStream object at a time.

Must Read, Multithreading in java, Duck Number in Java and Hashcode Method in Java

The need to store data in Files

  • When a program is terminated, all the data processed by the program is lost. Storing this data in a file preserves your data even after the termination of your program.
     
  • Consider a scenario where the input supplied to a program is large. It becomes difficult to enter each input one at a time. This problem can be solved if we were to store the input data in a file and let the program access it during execution.
     
  • Storing data in files help transfer it from one system to another without any changes of difficulty. It also serves as a backup to store important information in a remote location in case of any system failures.
     

Also see,  Swap Function in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

FileOutputStream

It belongs to the java.io package and extends the abstract OutputStream class. An output stream sends the output bytes it receives to some sink.

Syntax:

public class FileOutputStream extends OutputStream

Constructors

  • FileOutputStream(File file):

    • It creates a file output stream to write into a file specified by the given file object.
       
FileOutputStream f = new FileOutputStream(File file);

 

  • FileOutputStream(File file, boolean append):

    • It creates a file output stream to write into a file specified by the given file object.
       
    • The append parameter tells if an existing file is to be overwritten or appended. If append is true, then append the file; otherwise, overwrite the file.
       
FileOutputStream f = new FileOutputStream(File file, (true/false));

 

  • FileOutputStream(FileDescriptor fd)

    • It creates a file output stream to write to the specified file descriptor that represents an existing connection to a file in the system.
       
    • FileDescriptor helps open a file with a specific name and erases the file contents if any. Instances of a FileDescriptor serve as a handle to open a structure that may represent an open file, socket or any other source of bytes.
       
FileOutputStream f = new FileOutputStream(File file, (true/false));

 

  • FileOutputStream(String name)

    • It creates a file output stream to write to a file with the specified name.
       
FileOutputStream f = new FileOutputStream(String fname);

 

  • FileOutputStream(String name, boolean append)

    • It creates a file output stream to write to a file with the specified name.
       
    • The append parameter tells if an existing file is to be overwritten or appended. If append is true, then append the file; otherwise, overwrite the file.
       
FileOutputStream f = new FileOutputStream(String fname, true/false));

Methods/Functions

Method

Description

void close() It closes the file out stream and releases all resources associated with it.
protected void finalize() It cleans and finalises the connection to a file. It also ensures that the close function is called only when there are no references to this file output stream.
FileChannel getClannel() It returns the unique FileChannel object associated with the file output stream.
FileDescriptor getFD() It returns the file descriptor associated with this stream.
void write(byte[ ] b) It writes bytes of length b from a byte array to the file output stream.
void write(byte[ ] b, int off, int len) It writes bytes of length b from a given offset in a byte array to the file output stream.
void write(int b) It writes a specific byte into the file output stream.

 

Example

The code shown below executes creating a new file named output.txt in the current working directory and writes ‘Hello World’. The flush() method clears the OutputStream and ensures that all the data gets stored at the destination.

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

public class Main 
{
  public static void main(String[] args)
  {
      String data = "Hello World";
      try {
             FileOutputStream f = new FileOutputStream("output.txt");
             // The getBytes() to convert a string into bytes array.
             byte[] array = data.getBytes();
             // writing the file byte by byte
             f.write(array);
             f.close();
          }
      catch (Exception e) {
        System.out.println("An error occured");
      }
   }
}

 

Output:

Usually, data is sent to the OutputStream only when the buffer is full. The flush() method clears the OutputStream and ensures that all the data gets stored at the destination.
 

import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.util.*;
public class Main
{
  public static void main(String[] args)
  {
      try{
            FileOutputStream os = new FileOutputStream("file.txt");  
            FileInputStream is = new FileInputStream("file.txt");  
            os.write('A');  
            os.flush();  
            os.write('B');  
            System.out.println("" +(char) is.read());  
        }
      catch(Exception ex){
          System.out.println(ex);
        }
  }
}

 

Output:

A


Practice by yourself on java online compiler.

FAQs

  1.  What is a stream?
    A Stream is a logical connection between the Java program and a file that is used to exchange a sequence of bytes. Based on the direction of data flow, it could be an Input stream or Output stream to read inputs and deliver outputs, respectively. 
     
  2.  What is a FileChannel?
    A file channel is used for reading, writing, mapping, and manipulating a file. It allows to read or write at a specific position in the file. Multiple concurrent threads can use file channels safely as specific regions in the file can be locked for a single thread.

Key Takeaways

This article extensively discusses the FileOutputStream class in Java. We hope that this blog has helped you enhance your knowledge regarding the constructors and methods of the FileOutputStream class and if you would like to learn more, check out our articles on the Coding Ninjas Library. Do upvote our blog to help other ninjas grow. Happy Coding!

Related Links:

Previous article
File Input Stream class
Next article
BufferedInputStream and BufferedOutputStream
Live masterclass