Program opened below. You can scroll through the algorithm, Java code and output.

Read Names from a Text File

Download .java

Question

Read the names stored in a text file and display them one per line.

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
import 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();
    }
}
Input: File contents: Arunav Ray; Ankur Deria; Anuj Modi Output: Name 1: Arunav Ray Name 2: Ankur Deria Name 3: Anuj Modi
← Previous Program 39 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.