Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java.io.FilterOutputStream Class in Java
Next article icon

Creating a file using FileOutputStream

Last Updated : 11 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

FileOutputStream class belongs to byte stream and stores the data in the form of individual bytes. It can be used to create text files. A file represents storage of data on a second storage media like a hard disk or CD. Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileOutputStream (or other file-writing objects) at a time. In such situations, the constructors in this class will fail if the file involved is already open.

FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.

Important methods:

  • void close() : Closes this file output stream and releases any system resources associated with this stream.
  • protected void finalize() : Cleans up the connection to the file, and ensures that the close method of this file output stream is called when there are no more references to this stream.
  • void write(byte[] b) : Writes b.length bytes from the specified byte array to this file output stream.
  • void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array starting at offset off to this file output stream.
  • void write(int b) : Writes the specified byte to this file output stream.

Following steps are to be followed to create a text file that stores some characters (or text):

  1. Reading data: First of all, data should be read from the keyboard. For this purpose, associate the keyboard to some input stream class. The code for using DataInputSream class for reading data from the keyboard is as:
    DataInputStream dis =new DataInputStream(System.in);

    Here System.in represent the keyboard which is linked with DataInputStream object

  2. Send data to OutputStream: Now , associate a file where the data is to be stored to some output stream. For this , take the help of FileOutputStream which can send data to the file. Attaching the file.txt to FileOutputStream can be done as:
    FileOutputStream fout=new FileOutputStream(“file.txt”);
  3. Reading data from DataInputStream: The next step is to read data from DataInputStream and write it into FileOutputStream . It means read data from dis object and write it into fout object, as shown here:
    ch=(char)dis.read();  fout.write(ch);
  4. Close the file: Finally, any file should be closed after performing input or output operations on it, else the data of the may be corrupted. Closing the file is done by closing the associated streams. For example, fout.close(): will close the FileOutputStream ,hence there is no way to write data into the file.

Implementation:




//Java program to demonstrate creating a text file using FileOutputStream
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
class Create_File
{
    public static void main(String[] args) throws IOException 
    {
        //attach keyboard to DataInputStream
        DataInputStream dis=new DataInputStream(System.in);
  
        // attach file to FileOutputStream
        FileOutputStream fout=new FileOutputStream("file.txt");
  
        //attach FileOutputStream to BufferedOutputStream
        BufferedOutputStream bout=new BufferedOutputStream(fout,1024);
        System.out.println("Enter text (@ at the end):");
        char ch;
  
        //read characters from dis into ch. Then write them into bout.
        //repeat this as long as the read character is not @
        while((ch=(char)dis.read())!='@')
        {
            bout.write(ch);
        }
        //close the file
        bout.close();
    }
}
 
 

If the Program is executed again, the old data of file.txt will be lost and any recent data is only stored in the file. If we don’t want to lose the previous data of the file, and just append the new data to the end of already existing data, and this can be done by writing true along with file name.

FileOutputStream fout=new FileOutputStream(“file.txt”,true);  

Improving Efficiency using BufferedOutputStream

Normally, whenever we write data to a file using FileOutputStream as:

fout.write(ch);

Here, the FileOutputStream is invoked to write the characters into the file. Let us estimate the time it takes to read 100 characters from the keyboard and write all of them into a file.

  • Let us assume data is read from the keyboard into memory using DataInputStream and it takes 1 sec to read 1 character into memory and this character is written into the file by FileOutputStream by spending another 1 sec.
  • So for reading and writing a file will take 200 sec. This is wasting a lot of time. On the other hand, if Buffered classed are used, they provide a buffer which is first filled with characters from the buffer which can be at once written into the file. Buffered classes should be used in connection to other stream classes.
  • First, the DataInputStream reads data from the keyboard by spending 1 sec for each character. This character is written into the buffer. Thus, to read 100 characters into a buffer, it will take 100 second time. Now FileOutputStream will write the entire buffer in a single step. So, reading and writing 100 characters took 101 sec only. In the same way, reading classes are used for improving the speed of reading operation.  Attaching FileOutputStream to BufferedOutputStream as:
    BufferedOutputStream bout=new BufferedOutputStream(fout,1024);

    Here ,the buffer size is declared as 1024 bytes. If the buffer size is not specified , then a default size of 512 bytes is used

Important methods of BufferedOutputStream Class:

  • void flush() : Flushes this buffered output stream.
  • void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array starting at offset off to this buffered output stream.
  • void write(int b) : Writes the specified byte to this buffered output stream.

Output:

C:\> javac Create_File.java  C:\> java Create_File  Enter text (@ at the end):  This is a program to create a file  @    C:/> type file.txt  This is a program to create a file  

Related Articles:

  • CharacterStream vs ByteStream
  • File Class in Java
  • File handling in Java using FileWriter and FileReader


Next Article
Java.io.FilterOutputStream Class in Java

N

Nishant Sharma
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

  • FileOutputStream in Java
    In Java, the FileOutputStream class is a subclass of OutputStream. It is used to write data to a file as a stream of bytes. FileOutputStream is commonly employed for writing primitive values into a file. FileOutputStream supports writing both byte-oriented and character-oriented data. Note: FileWrit
    7 min read
  • How to Read a File using Applet?
    In this article, we will learn how to read the content of the file using Java and display those contents using Applet. Approach UsedThe user should type the name of the file in the input field that asks for the filename in the output applet window. If the file is already present, it will display the
    2 min read
  • Creating Sheets in Excel File in Java using Apache POI
    Apache POI is an open-source java library to create and manipulate various file formats based on Microsoft Office. Using POI, one should be able to perform create, modify and display/read operations on the following file formats. For Example, java doesn’t provide built-in support for working with ex
    3 min read
  • Java FileInputStream Class
    FileInputStream class in Java is useful for reading data from a file in the form of a Java sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. Example: FileInputStream class to read data from f
    4 min read
  • Java.io.FilterOutputStream Class in Java
    java.io.FilterInputStream Class in Java Java.io.FilterOutputStream class is the superclass of all those classes which filters output streams. The write() method of FilterOutputStream Class filters the data and write it to the underlying stream, filtering which is done depending on the Streams. Decla
    5 min read
  • GZIPOutputStream Class in Java
    The java.util.zip package provides classes to compress and decompress the file contents. FileInputStream, FileOutputStream, and GZIPOutputStream classes are provided in Java to compress and decompress the files. The GZIPOutputStream class is useful for writing compressed data in GZIP file format. Ho
    3 min read
  • Java.util.zip.InflaterOutputStream class in Java
    This class implements an output stream filter for uncompressing data stored in the "deflate" compression format. Constructors InflaterOutputStream(OutputStream out) : Creates a new output stream with a default decompressor and buffer size. InflaterOutputStream(OutputStream out, Inflater infl) : Crea
    3 min read
  • How to Execute SQL File with Java using File and IO Streams?
    In many cases, we often find the need to execute SQL commands on a database using JDBC to load raw data. While there are command-line or GUI interfaces provided by the database vendor, sometimes we may need to manage the database command execution using external software. In this article, we will le
    5 min read
  • Java.io.ObjectOutputStream Class in Java | Set 1
    An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream. Only objects that support the java.io.Serializable in
    9 min read
  • Java.io.OutputStream class in Java
    This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink. Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output. Constructo
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences