Program opened below. You can scroll through the algorithm, Java code and output.
Program 38
Write Five Names to a Text File
Question
Accept five names and write them to a text file, one name per line.
Algorithm
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 program
Javaimport 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");
}
}Sample output
Input: Input: five names, one per prompt
Output: Output: Five names written to names.txt