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

Write Five Names to a Text File

Download .java

Question

Accept five names and write them to a text file, one name per line.

Step 1: Start the program and create a keyboard input stream. Step 2: Create a file-output stream for the file names.txt. Step 3: Connect a PrintWriter to the file-output stream. Step 4: Repeat the input process exactly five times. Step 5: Prompt the user to enter the next name. Step 6: Read the complete name from the keyboard. Step 7: Write the name to the file followed by a line separator. Step 8: Continue until all five names have been written. Step 9: Close the PrintWriter to ensure that buffered data is saved. Step 10: Display a confirmation message. Step 11: Stop the program.
Java
import java.io.*;
class WriteNames
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new FileWriter("names.txt"));
        for (int i = 1; i <= 5; i++)
        {
            System.out.print("Enter name " + i + ": ");
            String name = br.readLine();
            pw.println(name);
        }
        pw.close();
        System.out.println("Five names written to names.txt");
    }
}
Input: Input: five names, one per prompt Output: Output: Five names written to names.txt
← Previous Program 38 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.