digitization, transformation, binary

Class FileInputStream in Java

FileInputStream is a child class of InputStream class and is used to manage a  FileInput stream as an input stream for reading data from a File or from a FileDescriptor or from a String that represents the fully qualified pathname.

FileInputStream class uses actual data files as the basis for an input stream. An object of this class represents a text file that can be accessed in sequential order byte by byte.

FileInputStream provides a low-level interface for reading data from a file. We should wrap a
FileInputStream with a DataInputStream if you need a higher-level interface that can handle reading strings and binary data. We should also think about wrapping a FileInputStream with a
BufferedInputStream to increase reading efficiency.

Data must be read sequentially from a FileInputStream; we can skip forward, but we cannot move back. If we need random access to file data, we need to use the RandomAccessFile class instead.

read() reads a byte or array of bytes from the file. It returns -1 when the end of file has been
reached. To read binary data, we typically use this class in conjunction with a BufferedInputStream and DataInputStream.

To read the text, we typically use it with an InputStreamReader and BufferedReader and Call
close() to close the file when input is no longer needed.

The class structure of FileInputStream is given as:

public class java.io.FileInputStream extends java.io.InputStream{
//constructors
public FileInputStream(File file) throws FileNotFoundException;
public FileInputStream(FileDescriptor fdObj);
public FileInputStream(String name)throws FileNotFoundException;
//Methods
public native int available()throws IOException;//returns the number of bytes of input currently available for reading.
public native int read()throws IOException;//returns an integer representation of the next available byte of input.
public int read(byte b[])throws IOException;//attempts to read up to b.length bytes into b and returns the actual number of the bytes that were successfully read.
public int read(byte b[],int offSet,int length)throws IOException;//attempts to read up to length bytes into b starting at b[offSet] returning the number of bytes successfully read. 
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 native long skip(long l)throws IOException;//skips over l bytes of input and returning the number of bytes skipped.
} 

In addition, all methods may throw an IOException if an IO error occurs apart from their regular Exceptions. All of the constructors can throw a SecurityException if the application does not have permission to read from the specified file.
The details of the class structure are given as follows:

public FileInputStream(String name);

public FileInputStream(String name) constructor creates a FileInputStream that gets its input from the file named by the specified String. It creates a FileInputStream object to read from the specified File object.

READ  LineNumberReader class in java

It may throw FileNotFoundException if the file is not available. 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.
Parameter
name -A String that contains the pathname of the file to be accessed. The path must conform to
the requirements of the native operating system.

public FileInputStream(File file);

public FileInputStream(File file) constructor creates a FileInputStream that gets its input from the file represented by the specified File. It creates a FileInputStream object to read from the specified File object. It may throw FileNotFoundException if the file is not available.
Parameter
file -The File to use as input.

public FileInputStream(FileDescriptor fdObj);

public FileInputStream(FileDescriptor fdObj) constructor creates a FileInputStream that gets its input from the file identified by the given FileDescriptor.

It creates a FileInputStream object to read from the specified FileDescriptor object. 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 to read from the specified FileDescriptor. This may result in a SecurityException.
Parameter
fdObj -The FileDescriptor of the file to use as input.

public native int available();

public native int available() method returns the number of available bytes of data. Initially, this is the length of the file.
This method returns the number of bytes that can be read from the file without blocking.

public native void close();

public native void close() method closes this file input 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 FileInputStream.
This method returns the file descriptor for the file that supplies data for this stream.

public native int read();

public native int read() method reads the next byte of data from the file. The method blocks if no input is available.
This method returns the next byte of data or -1 if the end of the stream is encountered.

public int read(byte[] b);

public int read(byte[] b) method reads data into the given array. The method fills the array if enough bytes are available.

READ  How change the default port of Netbeans and Glassfish ?

The method blocks until some input are available.

This method returns the actual number of bytes read or -1 if the end of the stream is encountered immediately.
Parameter
b – An array of bytes to be filled from the stream.

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

public int read(byte[] b, int off, int len) method reads len bytes of data into the given array, starting at element off. The method blocks until some input is available.

This method returns the actual number of bytes read or -1 if the end of the stream is encountered immediately.

Parameter
b -An array of bytes to be filled from the stream.
off – An offset into the byte array.
len – The number of bytes to read.

public native long skip(long n);

public native long skip(long n) method skips n bytes of input in the stream.

This method returns the actual number of bytes skipped.

Parameter
n -The number of bytes to skip.

protected void finalize();

protected void finalize() method is called when the FileInputStream 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.

Apart from these FileInputStream 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)

FileInputStream class also has inherited methods from class- Object. They are as follows:

  • markSupported()
  • reset()
  • mark(int)

An Example of FileInputStream


class InputStreamTest{
public static void main(String args[])
{
int size;
FileInputStream fin=new FileInputStream("C:TestmyFile.txt");
size=fin.available();
System.out.println("Total bytes"+size);
for(int i=0;i<size/4;i++)
System.out.println((char)fin.read());
System.out.println("remaining bytes"+fin.available());
System.out.println("remaining 1/4 is displayed :using read(b[]");
byte b[]=new byte[size/4];
if(fin.read(b)!=b.length)
{
System.out.println("File reading error");
}
else
{
String temp=new String(b,0,0,,b.length);//converts bytes to ASCII code
System.out.println(temp);
System.out.println("Still available :"+fin.available());
System.out.println("skipping 1/4: using skip()");
fin.skip(size/4);
System.out.println("file remaining for reading"+fin.available());
}
fin.close();
}
}
 

FileInputStream object can be opened in the following way:

  1. FileInputStream fin;
    fin=new FileInputStream(String name);//name indicates the source file
  2. File myFile;
    FileInputStream fin;
    myFile=new File(String name);
    fin=new FileInputStream(myFile);

FileInputStream 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  Dangling Else Problem in Java

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here