Java Program to read a file Line by Line .
Objective
Write a Java program to read a file line-by-line using the Scanner class.
Algorithm / Approach
- Prompt the user for a filename.
- Open a
FileInputStream. - Pass the stream into a new Scanner object:
Scanner sc2 = new Scanner(fis);. - Use a
while(sc2.hasNext())loop to check if more lines exist. - Use
sc2.nextLine()to extract the entire line as a String and print it. - Close the stream.
ReadFile.java
import java.util.*;
import java.io.*;
class ReadFile {
public static void main(String[] a)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter File Name: ");
String fileName = sc.nextLine();
Scanner sc2 = null;
FileInputStream fis = null;
try {
fis=new FileInputStream(fileName);
sc2 = new Scanner(fis);
while(sc2.hasNext()) {
String data = sc2.nextLine();
System.out.println(data);
}
}
catch(Exception e) {
System.out.print(e);
}
finally {
try {
fis.close();
}
catch(Exception e) { }
}
}
}
Expected Output
Enter File Name: Expense.txt java prowess 3 Developers
Explanation of the Program
- While
FileReaderreads one character at a time, it is often much more practical to process text files line by line. - The
Scannerclass is not just for reading keyboard input! By passing aFileInputStreaminto its constructor instead ofSystem.in, you instruct the Scanner to tokenize the file. - This is one of the cleanest and easiest ways to parse configuration files or CSV data.
Complexity
Time Complexity
O(n) - Where n is the number of lines in the file.
Space Complexity
O(m) - Where m is the length of the longest line (loaded into memory).