In our last post we learned about writing data into a file,in this tutorial we shall learn how to read the data from the file.To read the data from the file we need to use the object of the class File streams.
There are different types of File Stream classes in java.Reading data from the file is same as getting the data.Therefore we need to use FileInputStream object to read the data.
The methods provided by the FileInputStream class are available(), read().The procedure for reading the data is, first we need to bind the text file to the object of the FileInputStream.This is done by
FileInputStream fis = new FileInputStream("Name_of_the_File");
After binding the file to the object we need to find the available data in the file using the method available().We invoke this method using the object to which the file is bounded. After knowing the amount of data present in the file, we need to read the data.Since the data is written in the bytes we need to typecast the data into char for displaying the data to the user.Now the entire program is
import java.util.*; import java.io.*; class fileread { public static void main(String arg[]) { try { FileInputStream fis = new FileInputStream("f1.txt"); int available = fos.available(); System.out.print("\n\n\t\t"); for(int i=0;i<available;i++) { System.out.print((char)fos.read()); } fos.close(); } catch(Exception e) { System.out.print(e); } } }
Pingback: Copying data from one file to other file using java | letusprogram...!!!