Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Program: Create a program that has a menu with a number of options, at leas

ID: 441662 • Letter: J

Question

Java Program: Create a program that has a menu with a number of options, at least including the following: a. Write mode: accepts user input and writes it to a file (also named by the user). b. Read mode: accepts a file name and writes the contents to the screen for the user to read. c. Append mode: accepts user input and writes it to the end of a file. d. Accept a command line argument for a file, which it prints right away. e. When writing to a file your program ask for confirmation before overwriting.

Explanation / Answer

Reading a file involves a few steps. First a File object must be opened, then it must be attached to a FileInputStream and the BufferedReader. File input/output streams and associated objects throw errors and must be caught with try/catch statements.

Create the file ReadFileEx.java

First verify a file was specified on the command line. Next open a new FileInputStream with the first command line argument and attach the FileInputStream to a BufferedReader. The BufferedReader provides the interfaces to pull data from the file. While the BufferedReader buffer is ready to be read from read a line from the file and print to the screen. The boolean method ready will return true as long as there are bytes available in the buffer.

Writing a file is similar to reading files, except a FileOutputStream is opened and attached to a PrintStream.

Create WriteFileEx.java

First setup a FileOutputSream out and a PrintStream prt. These two variables will be used to write the file. Verify a filename was specified on the command line. Then open the FileOutputStream followed by initializing the PrintStream. Print out a couple of lines to the file. Finally close the file.

In this example the FileWriter class is going to be used to append text to the end of a file.

Create AppendFileEx.java

First declare the FileWriter object out. Next verify the file to append to was specified on the command line, and open the file. If true is appended as an option when initializing the FileWriter append mode is used. Then use the write method to append to the file. Notice that the linefeed must manually be appended when using the write method of FileWriter. Finally close the file.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote