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, FileWriter is more preferred.

What is meant by storing data to files?

Writing data to a File

Through the above image, we can understand that when we run the java program, the data is stored in the RAM. Now, suppose the variable data stored in RAM, we want to access that data and bring it to a file in our hard disk. So, we will create an object of OutputStream in the RAM and that will point to a file referencing to hard disk.

Now, the data from the variable data file in the RAM will go to the referencing file (object of Output Stream) and from there will be transferred/stored in the file of the hard disk.

Hierarchy of FileOutputStream

Hierarchy of FileOutputStream

Constructors of FileOutputStream

1. FileOutputStream(File file): Creates a file output stream to write to the file represented by the specified File object.

FileOutputStream fout = new FileOutputStream(File file);

2. FileOutputStream( File file, boolean append): Creates a file output stream object represented by specified file object.

FileOutputStream fout = new FileOutputStream(File file, boolean append);

3. 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.

FileOutputStream fout = new FileOutputStream(FileDescripter fdobj);

4. FileOutputStream( String name): Creates an object of file output stream to write to the file with the particular name mentioned.

FileOutputStream fout = new FileOutputStream( String name);

5. FileOutputStream( String name, boolean append): Creates an object of file output stream to write to the file with the specified name.

FileOutputStream fout = new FileOutputStream( String name, boolean append);

Declaration:

public class FileOutputStream extends OutputStream

Steps to write data to a file using FileOutputStream:

FileOutputStream fout = new FileOutputStream(“file1.txt”);
fout.write();
fout.close()

Example:

We need to import the java.io package to use FileOutputStream class.