Class FileOutputStream in Java

digitization, transformation, binary

FileOutputStream in Java:

A FileOutputStream is an output stream for writing data to a File or to a FileDescriptor.
FileOutputStream is useful to write some text to a text file. Like other streams we need to open the file first, then we will be able to write something in it.

The FileOutputStream class represents a byte stream that writes data to a file. The file can be specified using a FileDescriptor, a File object, or a String that represents a pathname. All of the constructors can throw a SecurityException if the application does not have permission to write to the specified file.

Ads code goes here

FileOutputStream provides a low-level interface for writing data to a file. We need to wrap a FileOutputStream with a DataOutputStream or a PrintStream if we need a higher-level interface that can handle writing strings and binary data.

we can also think about wrapping a FileOutputStream with a BufferedOutputStream to increase writing efficiency.

Data must be written sequentially to a FileOutputStream; we can either overwrite existing data or append data to the end of the file. If we need random access to file data, use the RandomAccessFile class instead.

write() writes a byte or array of bytes to the file. To write binary data, we typically use this class in conjunction with a BufferedOutputStream and a DataOutputStream. To write text, we typically use it with a PrintWriter, BufferedWriter, and an OutputStreamWriter. We need to use close() to close a FileOutputStream when no further output will be written to it.

The class structure of FileOutputStream is given as below:

public class java.io.FileOutputStream extends java.io.OutputStream{
//constructors
public FileOutputStream (File file) throws IOException;
//create a FileInputStream object to write to the specified File object. It may throw IOException if the file is not available or could not be opened for writing. It may also throw SecurityException if a security manager exists, and it's checkWrite() method is called with the file descriptor to see if the application is allowed to write access to the specified File.This may result in a SecurityException.
public FileOutputStream (FileDescriptor fdObj) throws IOException; //create a FileInputStream object to write to the specified FileDescriptor object. It may throw SecurityException if a security manager exists, and it's checkWrite() method is called with the file descriptor to see if the application is allowed to write access to the specified FileDescriptor or file. This may result in a SecurityException.
public FileOutputStream (String name, boolean append) throws IOException; 
public FileOutputStream (String name) throws IOException; //create a FileInputStream object to write to the specified File object. It may throw IOEception if the file is not available or could not be opened for writing. It may throw SecurityException if a security manager exists, and its checkRead() method is called with the file descriptor to see if the application is allowed read access to the file. This may result in a SecurityException.
//Methods
public native void close() throws IOException;//closes the input source; further read attempt on a closed input will generate an IOException.
protected void finalize()throws IOException;
public final FileDescriptor getFD() throws IOException;
public void write(byte b[])throws IOException;//writes an entire byte array i.e block of bytes at a time.
public void write(byte b[], int offset, int length)throws IOException;//write out length number of bytes from the block of bytes b starting at offset offset.
public native void write(int b)throws IOException;//writes one byte at a time
} 

The details of the class structure are given as follows:

public FileOutputStream(String name);

public FileOutputStream(String name) constructor creates a FileOutputStream that sends its output to the file named by the specified String.
Parameter
name -A String that contains the pathname of the file to be used for output. The path must conform
to the requirements of the native operating system.

public FileOutputStream(String name, boolean append); // New in 1.1

public FileOutputStream(String name, boolean append); constructor creates a FileOutputStream that sends its output to the named file. If append is true, the stream is positioned at the end of the file, and data is appended to the end of the file.

READ  Old Fashioned Coding Style May Help Garbage Collector to Reclaim Memory Quickly

Otherwise, if the append is false, the stream is positioned at the beginning of the file, and any
previous data is overwritten.
Parameter
name – A String that contains the pathname of the file to be used for output. The path must conform to the requirements of the native operating system.
append – Specifies whether or not data is appended to the output stream.

public FileOutputStream(File file);

public FileOutputStream(File file) constructor creates a FileOutputStream that sends its output to the file represented by the specified File.
Parameter
file – The File to use as output.

public FileOutputStream(FileDescriptor fdObj);

public FileOutputStream(FileDescriptor fdObj) constructor creates a FileOutputStream that sends its output to the file identified by the given FileDescriptor.
Parameter
fdObj-The FileDescriptor of the file to use as output.

public native void close();

public native void close() method closes this file output stream and releases any resources used by it.

public final FileDescriptor getFD();

public final FileDescriptor getFD() method returns the file descriptor associated with the data source of this FileOutputStream.

This method returns the file descriptor associated with the data source of this FileOutputStream.

public native void write(int b);

public native void write(int b) method writes a byte containing the low-order eight bits of the given value to the output stream.
Parameter
b -The value to write to the stream.

public void write(byte[] b);

public void write(byte[] b) method writes the entire contents of the given array to the output stream.
Parameter
b – An array of bytes to write to the stream.

public void write(byte[] b, int off, int len);

public void write(byte[] b, int off, int len) method writes len bytes from the given array, starting at element off, to the output stream.
Parameter
b– An array of bytes to write to the stream.
off– An offset into the byte array.
len-The number of bytes to write.

protected void finalize();

protected void finalize() method is called when the FileOutputStream is garbage-collected to ensure that close() is called. If the stream has a valid file descriptor, the close() method is called to free the system resources used by this stream.

READ  Learn How to Structure of Automation Test Case Free And Fast in 2020

Apart from these FileOutputStream class also has inherited methods from class- Object. They are as follows:

  • clone()
  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • toString()
  • wait(long)

FileOutputStream class also has inherited one methods from OutputStream. That is as follows:

  • flush()

An Example of FileOutputStream


class FileOutputTest{
public static void main(String args[]){
byte buffer=new byte[512];
int i=0;
int size=0;
String inFile=null;
String outFile=null;
FileInputStream fin;
FileoutputStream fout1,fout2;
try{
inFile=arg[0];//take input from user in command line
outFile=arg[1];
int c=0;
fout1=new FileOutputStream(arg[0]);
while((c.System.in.read())!=1){
//read from keyboard
buffer[i]=(byte)c;
i++;
}
size=i;
fout1.write(buffer);
fout1.close();
fin=new FileInputStream(arg[0]);
fout2=new FileOutputStream(arg[0]);
fin.read(buffer);
for(int i=0;i<buffer.length;i++)
{
fout2.write(buffer[i]);
}
if(size==i)
{
System.out.println("File successfully copied");
}
else
{
System.out.println("File copy error");
}
}
catch(ArrayIndexOutOfBoundException e)
{
System.out.println("File handling error");
}
}
}
 

We can append a file by using FileOutputStream.
FileOutputStream object can be opened in the following way:

  1. FileOutputStream fout;
    fout=new FileOutputStream(String name);//name is the output file along with the path.
  2. File myFile;
    myFile=new File(String name);
    fout=new FileOutputStream(myFile)

FileOutputStream in Serialization

Let us create a class that we want to Serialize using Serializable interface.

import java.io.*;
public class MySerialization implements Serializable {
	
	public int x=5;
	transient int y=10;
	private float z= 2.0f;
	
	int getX() {
	return x;
	}
	int getY()
	{
		return y;
	}
	float getZ() {
		return z;
	}
}

Check here we have a transient data y.
Now lets us create a class that helps in Serialization


import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class MyDemoSerialization {

	public static void main(String[] args) {
		MySerialization ms= new MySerialization();
		System.out.println("value of x "+ms.getX());
		System.out.println("value of y "+ms.getY());
		System.out.println("value of z "+ms.getZ());
		try {
			FileOutputStream fos=new FileOutputStream("D:\\MyCode\\abc.ser");
			ObjectOutputStream oos=new ObjectOutputStream(fos);
			oos.writeObject(ms);
			oos.close();
			System.out.println("Serialization is done");
			
		}
		catch(Exception e) {e.printStackTrace();}
	}

}

The output of the code:
value of x 5
value of y 10
value of z 2.0
Serialization is done
the y value is printed before Serialization

Serialization data created
Serialization data created

Now let us DeSerializa the same

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class MyDeSerialization {

	public static void main(String[] args) {
		System.out.println("Deserialization starts");
		MySerialization ms = null;
		try {
			FileInputStream fis=new FileInputStream("D:\\MyCode\\abc.ser");
			ObjectInputStream ois=new ObjectInputStream(fis);
			 ms = (MySerialization)ois.readObject();
			ois.close();
		}
		catch(Exception e) {e.printStackTrace();}
		System.out.println("value of x "+ms.getX());
		System.out.println("value of y "+ms.getY());
		System.out.println("value of z "+ms.getZ());
	}

}

The output of the code:
Deserialization starts
value of x 5
value of y 0
value of z 2.0

READ  Operators in Java

Check the y value is not saved as it is transient.

Share and Enjoy !

Leave a Comment

Your email address will not be published. Required fields are marked *