Program opened below. You can scroll through the algorithm, Java code and output.
Program 39
Read Names from a Text File
Question
Read the names stored in a text file and display them one per line.
Algorithm
Step 1: Start the program and open names.txt for reading.
Step 2: Connect a BufferedReader to the file reader.
Step 3: Initialise a counter to one.
Step 4: Read the first line from the file.
Step 5: Check whether the returned line is null, indicating the end of the file.
Step 6: If a line is available, display it with the current counter.
Step 7: Increase the counter by one.
Step 8: Read the next line and repeat the test.
Step 9: Continue until the end of the file is reached.
Step 10: Close the BufferedReader after reading is complete.
Step 11: Stop the program.
Java program
Javaimport java.io.*;
class ReadNames
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader("names.txt"));
String name;
int i = 1;
while ((name = br.readLine()) != null)
{
System.out.println("Name " + i + ": " + name);
i++;
}
br.close();
}
}Sample output
Input: File contents: Arunav Ray; Ankur Deria; Anuj Modi
Output: Name 1: Arunav Ray
Name 2: Ankur Deria
Name 3: Anuj Modi