Read Text File in Java

This Simple Java Program is for Reading a Text File in Java. This is a part of Mumbai University MCA Colleges Java Practicals. 

Reading a File in Java requires you to include or import java.io file. There are many different classes used for reading a file or byte stream in java. FileInputStream is most commonly used. To write to a file we will use FileOutputStream. We can read different types of files with this


The Below program opens a file named demofile.txt from a specified location (You can change the file you want to read). It then reads the file line by line using the read() function of FileInputStream Class. The read() function will return a -1 if it encounters end of file (EOF). 

import java.io.*;
class filedisplay
{
public static void main(String ar[])
{
File f_input=new File("D:/demo/java/demofile.txt");   //You can change the file 
try
{
FileInputStream fis=new FileInputStream(f_input);
int t=fis.read();
while(t!=-1)
{
System.out.print((char)t);
t=fis.read();
}
fis.close();
}
catch(Exception e)
{
System.out.print(e);
}
}
}

Hope this Java Program is useful to you in some sense or other. Keep following this blog for more Mumbai University MCA College Programs and simple Programs. Happy Programming and Studying

No comments:

Post a Comment