0% found this document useful (0 votes)
4 views1 page

Java File Reader with Line Numbers

This Java program reads a specified file and displays its contents on the screen with line numbers prefixed to each line. It handles file reading using BufferedReader and includes error handling for file access issues. The program requires a filename as a command-line argument and ensures proper resource management by closing the file reader after use.

Uploaded by

dannyhumble361
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

Java File Reader with Line Numbers

This Java program reads a specified file and displays its contents on the screen with line numbers prefixed to each line. It handles file reading using BufferedReader and includes error handling for file access issues. The program requires a filename as a command-line argument and ensures proper resource management by closing the file reader after use.

Uploaded by

dannyhumble361
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java program that reads a file and displays the file on the screen, with a line number before

each
line.
import [Link];
import [Link];
import [Link];

public class DisplayFileWithLineNumbers {


public static void main(String[] args) {
if ([Link] != 1) {
[Link]("Usage: java DisplayFileWithLineNumbers <filename>");
return;
}

String filename = args[0];


BufferedReader reader = null;

try {
reader = new BufferedReader(new FileReader(filename));
String line;
int lineNumber = 1;

while ((line = [Link]()) != null) {


[Link](lineNumber + ": " + line);
lineNumber++;
}

} catch (IOException e) {
[Link]("An error occurred: " + [Link]());
} finally {
try {
if (reader != null) [Link]();
} catch (IOException e) {
[Link]("Failed to close the file.");
}
}
}
}

You might also like