Question

In: Computer Science

The four methods needed for the assignment are specified in the Main class. Include a documentation...

The four methods needed for the assignment are specified in the Main class. Include a documentation comment with proper annotations for each of these four methods. Keep in mind that all four methods will be static and void. Additionally, there should be no throws clauses for any of the methods of this program. All exceptions should be properly handled with try-catch blocks. Refer to the following directions for each of the makeFile,readFile, writeFile, and deleteFile methods, respectively:

●Use the createNewFile() method of Java’s File class to add files to a subdirectory (folder)within the project directory. Let the user know if the file was successfully created or if anything goes wrong during the file creation process.

●Read from files using the Scanner class. Be sure to properly handle any exceptions inthe event that the file cannot be found or that the contents of the file cannot be read.Print the contents of the file to the console.

●Write to files using a combination of the FileWriter and PrintWriter classes. New content should be appended to the file rather than overwriting the current contents. Check that the file exists and throw an exception if it does not; do not rely on the PrintWriter class to create a new file to write to. Be sure to properly handle any exceptions in the event that the file cannot be found or that content cannot be written to the file.

●Use the delete() method of Java’s File class to delete files from the subdirectory. Let the user know if the file was successfully deleted or if anything goes wrong during the file deletion process.

The program used is Java script and requires two classes for the project, one- Main class and the second- FileHandler class. the File handler class should be able to create, read, write, and delete files.

public class Main
{
   public static void main(String[] args)
   {
       Scanner keyboard = new Scanner(System.in);   // Scanner object to read user input
       String fileName = "";                       // The name of a file to perform actions on
       String content = "";                       // Content to be written to a file
       String line = "";                           // An individual line of content
       int choice = -1;                           // User's selection

       while (choice != 5)
       {
           System.out.println("1. Create a file\n2. Read from a file\n3. Write to a file\n" +
               "4. Delete a file\n5. Exit the program");
           System.out.print("Please enter the number of your selection: ");
           choice = keyboard.nextInt();

           keyboard.nextLine();

           switch (choice)
           {
               // Create a new file
               case 1:
                   System.out.print("Please enter the name of the new file: ");
                   fileName = keyboard.nextLine();
                   FileHandler.makeFile(fileName);
                   break;
               // Read from a file
               case 2:
                   System.out.print("Please enter the name of the file to read: ");
                   fileName = keyboard.nextLine();
                   FileHandler.readFile(fileName);
                   break;
               // Write to a file
               case 3:
                   System.out.print("Please enter the name of the file to write to: ");
                   fileName = keyboard.nextLine();
                   line = "";

                   do
                   {
                       System.out.print("Please enter content to be added to the file ('end' to stop): ");
                       line = keyboard.nextLine();

                       if (!line.equals("end"))
                           content += line + "\n";
                   } while (!line.equals("end"));
                   FileHandler.writeFile(fileName, content);
                   break;
               // Delete a file
               case 4:
                   System.out.print("Please enter the name of the file to delete: ");
                   fileName = keyboard.nextLine();
                   FileHandler.deleteFile(fileName);
                   break;
               // Exit the program
               case 5:
                   break;
               // Warning for invalid input
               default:
                   System.out.println("Please enter a number from 1-5");
           }
       }
      
   }
}

Solutions

Expert Solution

Short Summary:

Ø  There is a defect in the given main method. Content has to be cleared before getting input for next try.

See the highlighted line in the main method

Ø  FileHandler class does all the file operations with the subdirectory. User has to provide relative path always and it creates/reads/writes and deletes the file from the sub directory

Ø  Created a method ‘getSubDirectoryFile’ in FileHandler which maps the input file to sub directory file.

Ø  All the methods in FileHandler class are static and handled all the exceptions appropriately.

Source Code:

Main.java file:

import java.util.Scanner;

public class Main

{

   public static void main(String[] args)

   {

       Scanner keyboard = new Scanner(System.in);   // Scanner object to read user input

       String fileName = "";                       // The name of a file to perform actions on

       String content = "";                       // Content to be written to a file

       String line = "";                           // An individual line of content

       int choice = -1;                           // User's selection

       while (choice != 5)

       {

           System.out.println("1. Create a file\n2. Read from a file\n3. Write to a file\n" +

               "4. Delete a file\n5. Exit the program");

           System.out.print("Please enter the number of your selection: ");

           choice = keyboard.nextInt();

           keyboard.nextLine();

          switch (choice)

           {

               // Create a new file

               case 1:

                   System.out.print("Please enter the name of the new file: ");

                   fileName = keyboard.nextLine();

                   FileHandler.makeFile(fileName);

                   break;

               // Read from a file

               case 2:

                   System.out.print("Please enter the name of the file to read: ");

                   fileName = keyboard.nextLine();

                   FileHandler.readFile(fileName);

                   break;

               // Write to a file

               case 3:

                   System.out.print("Please enter the name of the file to write to: ");

                   fileName = keyboard.nextLine();

                   line = "";

                 //Clear the content before getting content for next try

                   content = "";

                   do

                   {

                       System.out.print("Please enter content to be added to the file ('end' to stop): ");

                       line = keyboard.nextLine();

                       if (!line.equals("end"))

                           content += line + "\n";

                   } while (!line.equals("end"));

                   FileHandler.writeFile(fileName, content);

                   break;

               // Delete a file

               case 4:

                   System.out.print("Please enter the name of the file to delete: ");

                   fileName = keyboard.nextLine();

                   FileHandler.deleteFile(fileName);

                   break;

               // Exit the program

               case 5:

                   break;

               // Warning for invalid input

               default:

                   System.out.println("Please enter a number from 1-5");

           }

       }

     

   }

}

FileHandler.java File:

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Scanner;

public class FileHandler {

   

    final static String SUB_DIRECTORY = "Data";

   

    static String getSubDirectoryFile(String fileName){

        return SUB_DIRECTORY + "\\" + fileName;

    }

   

    /**

     * Adds the file to the sub directory within the project directory

     * @param fileName - to be created

     */

    static void makeFile(String fileName){

        // Use relative path

        File newfile = new File(getSubDirectoryFile(fileName));

      

        //Make sure that parent directory exists

        //If not, create the parent directory

        newfile.getParentFile().mkdirs();

        try {

            if(newfile.exists()){

                throw new IOException("File already exists");

           }

            else{         

                //Create the file using createNewFile() method

                newfile.createNewFile();

                //show a successful message, if it is created

                System.out.println("File has been created");

            }

        } catch (IOException e) {

            //If there is any exception, catch it and display it to user

            System.out.println("makeFile failed: " + e.getMessage());

        }

    }

    /**

     * Read lines from the file and displays on the console

     * @param fileName - to be read

     */

    static void readFile(String fileName) {

        try {

            //Create the scanner using file

            try (Scanner sc = new Scanner(new File(getSubDirectoryFile(fileName)))) {

                //Check if it has lines

                if(!sc.hasNext()){

                    System.out.println("File is empty");

                }

                else{

                    //Check if it is has line

                  while (sc.hasNext()) {

                        //Read the line and print it on the screen

                        String line = sc.nextLine();

                        System.out.println(line);

                    }

                }

            }

        } catch (IOException e) {

            //If there is any exception, catch it and display it to user

            System.out.println("readFile failed: " + e.getMessage());

        }

    }

    /**

     * Append the content into a file

     * @param fileName

     * @param content

     */

    static void writeFile(String fileName, String content) {

        try {

            //Create file object using File

            File file = new File(getSubDirectoryFile(fileName));

           

            //If the file does not exist, throw an exception

            if(!file.exists()){

                            throw new IOException("File does not exist " + fileName);

            }

            else{

                //Use file wirter and pass true to append the contenr

                FileWriter fw = new FileWriter(file,true);

                BufferedWriter bw = new BufferedWriter(fw);

                try (PrintWriter pw = new PrintWriter(bw)) {

                    //Write the content into the file

                    pw.print(content);

                }

                System.out.println("Content successfully appended at the end of file");

                bw.close();

                fw.close();

            }

        } catch (IOException e) {

            //If there is any exception, catch it and display it to user

            System.out.println("writeFile failed: " + e.getMessage());

        }

    }

    static void deleteFile(String fileName) {

        //If there is any exception, catch it and display it to user

        try

        {

            File file = new File(getSubDirectoryFile(fileName));

           

            //If the file does not exist, throw an exception

            if(!file.exists()){

                            throw new IOException("File does not exist " + fileName);

            }

            

            if(file.delete())                      //returns Boolean value

            {

                System.out.println(file.getName() + " deleted");   //getting and printing the file name

            }

            else

          {

                System.out.println(file.getName() + " file not deleted");

            }

         } catch (IOException e) {

            //If there is any exception, catch it and display it to user

            System.out.println("deleteFile failed: " + e.getMessage());

        }

    }

}

Sample Run:

Output files:

  • It adds the file to the sub directory which is same level as my project directory.

  • Initial Write:

  • After adding more lines:

******************************************************************************

Feel free to rate the answer and comment your questions, if you have any.

Happy Studying!!!

******************************************************************************


Related Solutions

C++ Assignment 1) Write a C++ program specified below: a) Include a class called Movie. Include...
C++ Assignment 1) Write a C++ program specified below: a) Include a class called Movie. Include the following attributes with appropriate types: i. Title ii. Director iii. Release Year iv. Rating (“G”, “PG”, “PG-13”, etc) - Write code that instantiates a movie object using value semantics as text: - Write code that instantiates a movie object using reference semantics: - Write the print_movie method code: - Write Constructor code: - Write Entire Movie class declaration
Challenge: Dog Description: Create a Dog class that contains specified properties and methods. Create an instance...
Challenge: Dog Description: Create a Dog class that contains specified properties and methods. Create an instance of Dog and use its methods. Purpose: This application provides experience with creating classes and instances of objects in C#. Requirements: Project Name: Dog Target Platform: Console Programming Language: C# Documentation: Types and variables (Links to an external site.) (Microsoft) Classes and objects (Links to an external site.) (Microsoft) Enums (Links to an external site.) (Microsoft) Create a class called Dog. Dog is to...
Problem: Implement a class named StringParser, along with specified methods, that can read words from a...
Problem: Implement a class named StringParser, along with specified methods, that can read words from a text file, parse those words (such as finding palindromes), and write those words to a new file More specifically: 1. Write the StringParser class so that it has the following methods: a) public static void main(String[] args) -- The main driver of the program. Prompts the user for an input file, an output file, and a choice for what kinds of words to output....
Description: Create a class in Python 3 named Animal that has specified attributes and methods. Purpose:...
Description: Create a class in Python 3 named Animal that has specified attributes and methods. Purpose: The purpose of this challenge is to provide experience creating a class and working with OO concepts in Python 3. Requirements: Write a class in Python 3 named Animal that has the following attributes and methods and is saved in the file Animal.py. Attributes __animal_type is a hidden attribute used to indicate the animal’s type. For example: gecko, walrus, tiger, etc. __name is a...
Overview For this assignment, design and implement the methods for a class that can be used...
Overview For this assignment, design and implement the methods for a class that can be used to represent a quadratic equation. int main() has already been written for this assignment. It is available for download from Blackboard or by using the following link: http://faculty.cs.niu.edu/~byrnes/csci240/pgms/240pgm8.cpp All that needs to be done for this assignment is to add the class definition and method implementation to the above CPP file. The Quadratic class Data Members The class contains three data members: an integer...
Implement the Nickel class. Include Javadoc comments for the class, public fields, constructors, and methods of...
Implement the Nickel class. Include Javadoc comments for the class, public fields, constructors, and methods of the class. I have added the Javadoc comments but please feel free to format them if they are done incorrectly. public class Nickel implements Comparable { private int year; /** * The monetary value of a nickel in cents. */ public final int CENTS = 5; /** * Initializes this nickel to have the specified issue year. * * @param year * * @pre....
Given the main method of a driver class, write a Fraction class. Include the following instance...
Given the main method of a driver class, write a Fraction class. Include the following instance methods: add, multiply, print, printAsDouble, and a separate accessor method for each instance variable. Write a Fraction class that implements these methods: add ─ This method receives a Fraction parameter and adds the parameter fraction to the calling object fraction. multiply ─ This method receives a Fraction parameter and multiplies the parameter fraction by the calling object fraction. print ─ This method prints the...
For this week's assignment please share with the class: 1. Why is closing process needed in...
For this week's assignment please share with the class: 1. Why is closing process needed in the accounting cycle? 2. Your understanding of the Income Summary account? 3. What happens to the Retained Earnings account in the closing process? 4. Your strategy for learning the closing process.
Needed in C++ In this assignment, you are asked to create a class called Account, which...
Needed in C++ In this assignment, you are asked to create a class called Account, which models a bank account. The requirement of the account class is as follows (1) It contains two data members: accountNumber and balance, which maintains the current account name and balance, respectively. (1) It contains three functions: functions credit() and debit(), which adds or subtracts the given amount from the balance, respectively. The debit() function shall print ”amount withdrawn exceeds the current balance!” if the...
package design; public class FortuneEmployee { /** * FortuneEmployee class has a main methods where you...
package design; public class FortuneEmployee { /** * FortuneEmployee class has a main methods where you will be able to create Object from * EmployeeInfo class to use fields and attributes.Demonstrate as many methods as possible * to use with proper business work flow.Think as a Software Architect, Product Designer and * as a Software Developer.(employee.info.system) package is given as an outline,you need to elaborate * more to design an application that will meet for fortune 500 Employee Information *...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT