Basic File Reading Example
This program demonstrates reading a file line by line.
Problem Statement
Write a Java program that reads a text file and prints its contents line by line.
Source Code
| 1 | import java.io.*; |
| 2 | public class FileReadExample { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq File Read Example"); |
| 5 | try(BufferedReader br=new BufferedReader(new FileReader("sample.txt"))) { |
| 6 | String line; |
| 7 | while((line=br.readLine())!=null){ |
| 8 | System.out.println("Eduinq Line: "+line); |
| 9 | } |
| 10 | } catch(IOException e) { |
| 11 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 12 | } |
| 13 | } |
| 14 | } |
Program Output
Eduinq File Read Example Eduinq Line: Hello Eduinq Eduinq Line: Welcome to File Handling
Explanation
File reading uses BufferedReader for efficient line-by-line reading. - Try-with-resources ensures automatic closure of streams. - Exception handling prevents crashes if file is missing. - In enterprise systems, file reading is essential for configuration and data input. Conclusion: Shows basic file reading in Java.