Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to read a file Line by Line .

Java Code Example — File Handling Programs

ADVERTISEMENT

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

  1. Prompt the user for a filename.
  2. Open a FileInputStream.
  3. Pass the stream into a new Scanner object: Scanner sc2 = new Scanner(fis);.
  4. Use a while(sc2.hasNext()) loop to check if more lines exist.
  5. Use sc2.nextLine() to extract the entire line as a String and print it.
  6. 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 FileReader reads one character at a time, it is often much more practical to process text files line by line.
  • The Scanner class is not just for reading keyboard input! By passing a FileInputStream into its constructor instead of System.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).
ADVERTISEMENT