Tenth Line
EASYDescription
Given a text file file.txt, print just the 10th line of the file.
Example:
Assume that file.txt has the following content:
Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10
Your script should output the tenth line, which is:
Line 10
1. If the file contains less than 10 lines, what should you output?
2. There's at least three different solutions. Try to explore all possibilities.
Approaches
Checkout 3 different approaches to solve Tenth Line. Click on different approaches to view the approach and algorithm in detail.
Iterative Reading with a Counter
A more memory-efficient approach is to read the file line by line, keeping track of the current line number. We stop reading and print the line as soon as we reach the 10th line.
Algorithm
- Initialize a line counter to 0.
- Open
file.txtusing aBufferedReader. - Read the file line by line in a loop.
- For each line, increment the counter.
- If the counter reaches 10, print the current line and exit the loop.
- If the end of the file is reached before the counter hits 10, do nothing.
This method avoids loading the entire file into memory. Instead, it processes the file as a stream. We use a BufferedReader to read the file one line at a time. A counter variable is initialized to 1 and incremented for each line read. When the counter equals 10, we've found our target line. We print it and can immediately stop processing the rest of the file by breaking the loop. If the loop finishes (i.e., we reach the end of the file) and the counter is less than 10, it means the file has fewer than 10 lines, and nothing is printed.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class IterativeRead {
public static void main(String[] args) {
String fileName = "file.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
int lineCount = 0;
while ((line = reader.readLine()) != null) {
lineCount++;
if (lineCount == 10) {
System.out.println(line);
break; // Stop reading after the 10th line
}
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}
Complexity Analysis
Pros and Cons
- Very memory efficient; suitable for files of any size.
- Time efficient, as it stops reading as soon as the target line is found.
- Slightly more verbose than the first approach.
- Does not provide random access to other lines without re-reading the file.
Video Solution
Watch the video walkthrough for Tenth Line
Similar Questions
5 related questions you might find useful
Tags:
No tags found.
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.