Read Text File in Java

Ram Pothuraju
This Simple Java Program is for Reading a Text File in Java. 

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);
}
}
}
Tags

Post a Comment

0Comments

Post a Comment (0)