Open In App

Creating a file using FileOutputStream

Last Updated : 11 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
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:



Similar Reads

FileOutputStream in Java
FileOutputStream is an outputstream for writing data/streams of raw bytes to file or storing data to file. FileOutputStream is a subclass of OutputStream. To write primitive values into a file, we use FileOutputStream class. For writing byte-oriented and character-oriented data, we can use FileOutputStream but for writing character-oriented data, F
5 min read
Creating a Cell at specific position in Excel file using Java
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/ it can be used to create a cell in a Given Excel file at a specific position. Apache POI is an API provided by the Apach
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 excel files, so we need to look for open-source APIs
3 min read
Creating and Executing a .jar File in Linux Terminal
JAR - Java Archive. It is like a zip file but for java classes. It combines all the .class files in Java into a single .jar file. It is used to download all java classes on HTTP in a single operation. These can be created using the "jar" CLI tool. It also has an optional META-INF which can include files like - MANIFEST.MF - manifest file is used to
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 learn how to execute an SQL file containing thousand
5 min read
Different Ways to Copy Content From One File to Another File in Java
In Java, we can copy the contents of one file to another file. This can be done by the FileInputStream and FileOutputStream classes. FileInputStream Class It is a byte input stream class which helps in reading the bytes from a file. It provides different methods to read the data from a file. FileInputStream fin = new FileInputStream(filename); This
3 min read
Java Program to Read Content From One File and Write it into Another File
File handling plays a major role in doing so as the first essential step is writing content to a file. For this is one must know how to write content in a file using the FileWriter class. The secondary step is reading content from a file and print the same. For this, one must have good hands on File Reader class to do so. Now in order to read conte
5 min read
How to Convert a Kotlin Source File to a Java Source File in Android?
We use Android Studio to translate our Java code into Kotlin while transitioning from Java to Kotlin. But what if we need to convert a Kotlin file to its Java equivalent? We'll examine how to convert a Kotlin source file to a Java source file in this blog. Let's get this party started. Because of its interoperability with Java, Kotlin grew at an ex
2 min read
How to Extract File Extension From a File Path String in Java?
In Java, working with Files is common, and knowing how to extract file extensions from file paths is essential for making informed decisions based on file types. In this article, we will explore techniques for doing this efficiently, empowering developers to improve their file-related operations. Program to extract file extension from a file path S
5 min read
How to Create a File with a Specific File Attribute in Java?
In Java, you can create a file with specific File attributes such as read-only, hidden, or system attributes. This allows you to control the behavior and visibility of the file in the File system. In this article, we'll explore how to create a file with specific attributes in Java. In this article, we will learn to create a file with a specific fil
2 min read
Article Tags :
Practice Tags :