Java Program to Read a File
This article covers a program in Java that reads a file, entered by user at run-time of the program.
Read a File Line by Line in Java
The question is, write a Java program to read a file, line by line using Scanner. The program given below is
its answer:
import java.util.Scanner;
import java.io.*;
public class CodesCracker
{
public static void main(String[] args)
{
String myfile, myline;
Scanner scan = new Scanner(System.in);
System.out.print("Enter File Name: ");
myfile = scan.nextLine();
try
{
FileReader fileReader = new FileReader(myfile);
BufferedReader bufread = new BufferedReader(fileReader);
// reading the file, line by line
while((myline = bufread.readLine()) != null)
System.out.println(myline);
bufread.close();
}
catch(IOException e)
{
System.out.println("Exception: " +e);
}
}
}
The snapshot given below shows the sample run of above program, with user input codescracker.txt as name of
file to read
In the above program, if you change the following block of code:
while((myline = bufread.readLine()) != null)
System.out.println(myline);
with the block of code given below:
int line_no = 1;
while((myline = bufread.readLine()) != null)
{
System.out.println("Line No." +line_no+ ": \"" +myline+ "\"");
line_no++;
}
then the output will be:
The while loop, can also be replaced with for. Here is the for loop version of the same
block, created using while:
int line_no = 1;
for(myline=bufread.readLine(); myline!=null; myline=bufread.readLine())
{
System.out.println("Line No." +line_no+ ": \"" +myline+ "\"");
line_no++;
}
The file codescracker.txt is already available inside the current directory. The directory in which the
above Java application's source code is saved.
Same Program in Other Languages
Java Online Test
« Previous Program
Next Program »