How to Read Input Until End of File (EOF) in Java
When dealing with input in Java, there might be situations where you don't know the number of lines you're going to read in advance. This is common in coding challenges or scenarios where you're reading from a file or stream until the end. In this post, Iβll show you a simple way to handle this using Java.
Problem Overview
Imagine you're given an unknown number of lines as input. Your task is to read all the lines until the end-of-file (EOF) and print each line, prefixed with its line number.
Here's what the input/output looks like:
Input:
Hello world
I am a file
Read me until end-of-file.
Output:
1 Hello world
2 I am a file
3 Read me until end-of-file.
The Java Approach
Java provides a handy way to handle such problems with the Scanner class and its hasNext() method. This method allows us to read input until there's no more data to read (EOF).
Code Solution
Letβs dive straight into the code:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for (int i = 1; sc.hasNext(); i++) {
String line = sc.nextLine();
System.out.println(i + " " + line);
}
sc.close();
}
}
Explanation
Import Required Packages: We import java.util.Scanner to use the Scanner class for reading input.
Initialize Scanner: We create a Scanner object to read from standard input (System.in).
Read Until EOF: The for loop is designed to read lines until there's no more input. The condition sc.hasNext() checks if there's more input to read. If there is, it reads the next line with sc.nextLine().
Print with Line Number: For every line read, we print it along with its line number. We use a loop counter i that starts from 1 and increments with each iteration.
Close Scanner: Although not strictly necessary here, it's a good practice to close the Scanner when you're done to avoid resource leaks.
Key Takeaways
- The Scanner class in Java, with its hasNext() method, is a great tool for reading input until EOF.
- Use sc.nextLine() to read each line of input.
- Keep track of the line number using a simple counter.
Final Thoughts
This approach is simple yet effective for reading an unknown number of lines until EOF in Java. It comes in handy during competitive programming, file reading tasks, or any situation where you're dealing with streams of data.
Top comments (0)