Advertisement



< Prev
Next >



Java - FileInputStream



FileInputStream class is a subclass of InputStream abstract class. FileInputStream is used to create an input stream, which is used to read byte/bytes from a file.




Constructors of FileInputStream :



Both the examples of constructors have created a FileInputStream object to create an input stream to read a file called TextBook.txt which is located in the D: drive.




Some methods for reading FileInputStream


Methods Description
available()
This method gives the remaining number of bytes available to read from this input stream.

read()
This method reads one byte from this input stream.

read(byte[] b)
This method reads a whole byte array from this input stream.

close()
This method closes this input stream and also frees any resources connected with this input stream.






We are reading an existing file called "TextBook.txt" using its path "D:\\TextBook.txt". Let's say the contents of this file "TextBook.txt" are-

TextBook.txt
 World peace is extremely important. 


//Java - Program to read one byte at a time through an existing file using FileInputStream.

import java.io.*;

class A
{
public static void main(String...ar)
{
try
{
	FileInputStream fin= new FileInputStream("D:\\TextBook.txt");
	int c;
	
	
	//Reading one byte out of a file
	while( (c=fin.read()) !=-1) 
	{
		//casting byte to char for displaying on the screen
		System.out.print((char)c); 
	}

	fin.close();
}

catch(IOException e)
{
	System.out.println(e);
}

}
}



Output is -:


World peace is extremely important


Program Analysis





Advertisement





In the next example, we are reading the contents of the same file TextBook.txt, but this time we are reading a whole byte array at once for faster reading.

//Java - Program to read a byte array out of an existing file using FileInputStream.
 
import java.io.*;

class A
{
public static void main(String...ar)
{
try
{
	FileInputStream fin= new FileInputStream("D:\\TextBook.txt");
	int num= fin.available();	
	System.out.println("Number of bytes available to read =" + num);
	
	byte b[]= new byte[num];
	
	int c;
	
	//read() method stops reading from file when EOF is reached i.e. -1	
	if((c=fin.read(b))!=-1) 
		System.out.println("Number of bytes read = " +c);

	String s= new String(b);
	System.out.println(s);
	fin.close();

}
catch(IOException e)
{
	System.out.println(e);
}

}
}



Output is -:


Number of bytes available to read =34
Number of bytes read = 34
World peace is extremely important


Program Analysis






Please share this article -




< Prev
Next >
< What is File?
FileOutputStream >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement