Question

In: Computer Science

java programming You will be given two interfaces and two abstract classes, FileTextReader, FileTextWriter, AbstractFileMonitor, and...

java programming

You will be given two interfaces and two abstract classes, FileTextReader, FileTextWriter, AbstractFileMonitor, and AbstractDictionary. Your job is to create two classes the first class should be named FileManager, the second class should be named Dictionary. The FileManager will implement the interfaces FileTextReader and FileTextWriter and extend the clas AbstractFileMonitor. Your class signature would look something like the following:

public class FileManager extends AbstractFileMonitor implements FileTextReader, FileTextWriter{...

The constructor signature of the FileManager should look like the following:

public FileManager(String filePath){...

The Dictionary will extend the abstract class AbstractDictionary. Your class signature would look something like the following:

public class Dictionary extends AbstractDictionary {...

The constructor signature of the Dictionary should look like the following:

public Dictionary(String path, FileManager fileManager) throws IOException {...

Please read the programmatic documentation of the two interfaces and abstract classes to gain an understanding of what each function should do. This assignment will test your knowledge of reading and writing to a text file, implementing interfaces, extending abstract classes, throwing exceptions and working with collections specifically sets.

This project is accompanied by two test classes, ManagerTest, and DictionaryTest. They will test the functionality of the functions in the interfaces and the abstract methods of classes. Its recommended that you implement the FileManager before working on the AbstractDictionary.

Abstract Dictionary

package homework;

import java.io.IOException;
import java.util.Objects;
import java.util.Set;


* A class that holds a collection of words read from a text file. The collection of words is used in the methods of this class
* methods provided in this class.


public abstract class AbstractDictionary {
  
   private final FileTextReader FILE_READER;
   private final Set ALL_WORDS;
  

   /**
   * Creates an abstract dictionary of words using the text file at the specified path.
   * @param path a path to a text file containing a dictionary of words
   * @param dictionaryFileReader the FileReader used to read from the text file at the specified path
   * @throws IOException thrown if there is a problem reading the file at the path
   */
  

public AbstractDictionary(String path, FileTextReader dictionaryFileReader) throws IOException {
       Objects.requireNonNull(dictionaryFileReader, "The File reader can not be null");
       Objects.requireNonNull(path, "The path can not be null");

      FILE_READER = dictionaryFileReader;

       ALL_WORDS = FILE_READER.getAllLines(path);
   }

  
   /**
   * Returns a set of all the words contained in the dictionary text file.
   * @return a set containing all the words in the dictionary file.
   */
  

public Set getAllWords(){
       return ALL_WORDS;
   }

   /**
   * Counts the number of words in this Dictionary that start with the specified prefix and have a length that is equal or greater
   * than the specified size. If size the specified size is less than 1 then word size is not taken into account.
   * @param prefix the prefix to be found
   * @param size the length that the word must equal or be greater than. If a value less than 1 is specified, all words regardless of their
   * characters size should be considered. In other words if the size parameter is < 1 word size is disregarded in the calculations.
   * @param ignoreCase if true this will ignore case differences when matching the strings. If false this considers
   * case differences when matching the strings
   * @return The number of words that start with the specified prefix
   * @throws IllegalArgumentException if the specified string is null or empty (Meaning contains no characters or only white space or blank)
   */

public abstract int countWordsThatStartWith(String prefix, int size, boolean ignoreCase) throws IllegalArgumentException;

   /**
   * Tests if this Dictionary contains at least one word with a length equal to or greater than the specified size that starts with the specified prefix.
   * If size the specified size is less than 1 then word size is not taken into account.
   * @param prefix the prefix to be found
   * @param size the length that the word must equal or be greater than. If a value less than 1 is specified, all words regardless of their
   * characters size should be considered. In other words if the size parameter is < 1 word size is disregarded in the calculations.
   * @param ignoreCase if true this will ignore case differences when matching the strings. If false this considers
   * case differences when matching the strings
   * @return The number of words that start with the specified prefix
   * @throws IllegalArgumentException if the specified string is null or empty (Meaning contains no characters or only white space)
   */
  

public abstract boolean containsWordsThatStartWith(String prefix, int size, boolean ignoreCase) throws IllegalArgumentException;
   * Returns a set of all the words within in this Dictionary that start with the specified prefix and have a length that is equal or greater
   * than the specified size. If size the specified size is less than 1 then word size is not taken into account.
   * @param prefix the prefix to be found
   * @param size the length that the word must equal or be greater than. If a value less than 1 is specified, all words regardless of their
   * characters size should be considered. In other words if the size parameter is < 1 word size is disregarded in the calculations.
   * @param ignoreCase if true this will ignore case differences when matching the strings. If false this considers
   * case differences when matching the strings
   * @return A list of all strings that start with the specified prefix
   * @throws IllegalArgumentException if the specified string is null or empty (Meaning contains no characters or only white space)

   public abstract Set getWordsThatStartWith(String prefix, int size, boolean ignoreCase) throws IllegalArgumentException;
}

AbstractFileMonitor

package homework;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
* A class with methods to monitor a text file.

public abstract class AbstractFileMonitor {

   private MessageDigest messageDigest;
   private int currentCheckSum;
   private boolean hasChanged = false;
   private long nextUpateTime = 0;
  
   public AbstractFileMonitor(String path){
setFilePath(path);
}

   * Updates the variables that correspond to the file being monitored
   * This function has been throttled such that it will only update values every 250 ms. In other words successive calls to this
   * function in time intervals that are less than 250 ms will yield no change.
   * @throws IOException Thrown if any type of I/O exception occurs while writing to the file
   * @throws IllegalStateException If the {@link #setFile(String)} method in not invoked with a proper file prior to invocation of this
   * @throws NoSuchAlgorithmException If the computer's OS is missing the SHA-256 hashing algorithm
   * method. In other words if no file is currently set to be monitored.

   public void update() throws IOException, IllegalStateException, NoSuchAlgorithmException {

      if(messageDigest == null){
           messageDigest = MessageDigest.getInstance("SHA-256");
       }
      
       if(nextUpateTime > System.currentTimeMillis()) {
           hasChanged = false;

          
          return;
       }

      
      nextUpateTime = System.currentTimeMillis() + 250;
      
       File file = new File(getFilePath());
      
       if(!file.exists()) return;

      
try (DigestInputStream dis = new DigestInputStream(new FileInputStream(getFilePath()), messageDigest)) {
while (dis.read() != -1) ;
messageDigest = dis.getMessageDigest();
}

StringBuilder result = new StringBuilder();
for (byte b : messageDigest.digest()) {
result.append(String.format("%02x", b));
}
  

hasChanged = currentCheckSum != result.toString().hashCode();
  
currentCheckSum = result.toString().hashCode();

   }
   * Tests if the file being monitored has changed since the last time {@link #update()} was invoked
   public boolean hasChanged(){
       return hasChanged;
}
   public abstract void setFilePath(String path);
   public abstract String getFilePath() throws IllegalStateException;
}

FileTextReader

package homework;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Set;


public interface FileTextReader{
   public String readText(String path) throws IOException;

   * @throws IOException Thrown if any type of I/O exception occurs while writing to the file

public Set getAllLines(String path) throws IOException;
   * @throws IOException Thrown if any type of I/O exception occurs while writing to the file
public String getLastLine(String path) throws IOException;
}

FileTextWriter

package homework;

import java.io.IOException;


public interface FileTextWriter {
   * @throws IOException Thrown if any type of I/O exception occurs while writing to the file
   * @throws IllegalArgumentException if the specified string is null or empty (Meaning contains no characters or only white space)
   public void writeToFile(String string, String path) throws IOException, IllegalArgumentException;
}

We need to create that two classes.

Solutions

Expert Solution

java code for FileManager class and Dictionary class and test classes for both are given below.

FileManager class

package filedemo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class FileManager extends AbstractFileMonitor implements FileTextReader, FileTextWriter{
    String filePath;
    public FileManager(String filePath){
        super(filePath);
        this.filePath=filePath;
    }

    @Override
    public void setFilePath(String path) {
        filePath=path;
    }

    @Override
    public String getFilePath() throws IllegalStateException {
        return filePath;
    }

    @Override
    public String readText(String path) throws IOException {
        String ot="";
        File file = new File(path); 
        BufferedReader br = new BufferedReader(new FileReader(file));  
        String st;
        while ((st = br.readLine()) != null) {
        ot+=st+"\n"; 
        } 
        return ot;
    }

    @Override
    public Set getAllLines(String path) throws IOException {
        Set<String> set = new HashSet<String>();
        File file = new File(path); 
        BufferedReader br = new BufferedReader(new FileReader(file));  
        String st;
        while ((st = br.readLine()) != null) {
        set.add(st);
        } 
        
        return set;
    }

    @Override
    public String getLastLine(String path) throws IOException {
        String st="";
        String ot="";
        File file = new File(path); 
        BufferedReader br = new BufferedReader(new FileReader(file));  
        while ((st = br.readLine()) != null) {
           ot=st;
        }
        return ot;
    }

    @Override
    public void writeToFile(String string, String path) throws IOException, IllegalArgumentException {
       File myObj = new File(path);
       if(myObj==null)
       {
           myObj.createNewFile();
       }
       else
       {
            FileWriter myWriter = new FileWriter(path);
            myWriter.write(string);
            myWriter.close();
       }
    }
}
    

ManagerTest class

/*
 * To test FileManager
 */
package filedemo;

import java.io.IOException;

public class ManagerTest {
    
    public void Test()throws IOException
    {
     String filename="E:\\Words.txt";
     String filenamew="E:\\Wordsw.txt";
     FileManager obj=new FileManager(filename);
     System.out.println("Read Text");
     System.out.println(obj.readText(filename));
     System.out.println("All Lines using set");
     System.out.println(obj.getAllLines(filename));
     System.out.println("Last line in file");
     System.out.println(obj.getLastLine(filename));
     obj.writeToFile("HaiWr", filenamew);
    }   
    
}

input

content in Words.txt

output

Dictionary Class

package filedemo;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Dictionary extends AbstractDictionary{
    Set<String> set = new HashSet<String>();
    public Dictionary(String path, FileManager fileManager) throws IOException {
        super(path,fileManager);
        set=getAllWords();
    
    }

    @Override
    public int countWordsThatStartWith(String prefix, int size, boolean ignoreCase) throws IllegalArgumentException {
        int count=0;     
        String st;       
        for(Iterator<String> it = set.iterator(); it.hasNext();) {
            st=it.next();
            if(ignoreCase)
            {
               prefix=prefix.toUpperCase();
               st=st.toUpperCase();               
            }
            if(st.startsWith(prefix) && st.length()>=size)
            {
                count++;
            }
         }        
        return count;
    }

    @Override
    public boolean containsWordsThatStartWith(String prefix, int size, boolean ignoreCase) throws IllegalArgumentException {
       
        boolean result=false;
        int count=0;
      
        String st;
        
        for(Iterator<String> it = set.iterator(); it.hasNext();) {
            st=it.next();
            if(ignoreCase)
            {
               prefix=prefix.toUpperCase();
               st=st.toUpperCase();               
            }
            if(st.startsWith(prefix) && st.length()>=size)
            {
                count++;
            }
         }
        if(count==0)
        {
            result=false;
        }else
        {
            result=true;
        }
        return result;
    }

    @Override
    public Set getWordsThatStartWith(String prefix, int size, boolean ignoreCase) throws IllegalArgumentException {
        Set<String> seto = new HashSet<String>();
         String st;       
        for(Iterator<String> it = set.iterator(); it.hasNext();) {
            st=it.next();
            if(ignoreCase)
            {
               prefix=prefix.toUpperCase();
               st=st.toUpperCase();               
            }
            if(st.startsWith(prefix) && st.length()>=size)
            {
                seto.add(st);
            }
         }        
        return seto;
    }
    
    
}

DictionaryTest class

/*
 * To test dictionary.
 
 */
package filedemo;

import java.io.IOException;

public class DictionaryTest {
    public void run() throws IOException    
    {
         String filename="E:\\Words.txt";       
        FileManager objf=new FileManager(filename);
        Dictionary obj=new Dictionary(filename,objf);
        System.out.println("Count of words start with He not ignore case");
        System.out.println(obj.countWordsThatStartWith("He", 0, false));
        System.out.println("exist or not words start with He ignore case");
        System.out.println(obj.containsWordsThatStartWith("He", 0, true));
        System.out.println("set of words start with He not ignore case");
        System.out.println(obj.getWordsThatStartWith("He", 0, false));
    }
    
}

Driver program


package filedemo;

import java.io.IOException;

public class FileDemo {

    public static void main(String[] args)throws IOException {
        ManagerTest obj=new ManagerTest();
        obj.Test();
        DictionaryTest dobj=new DictionaryTest();
        dobj.run();
    }
    
}

*please change the package name.

package filedemo; to your package name.

output


Related Solutions

java programming You will be given two interfaces and two abstract classes, FileTextReader, FileTextWriter, AbstractFileMonitor, and...
java programming You will be given two interfaces and two abstract classes, FileTextReader, FileTextWriter, AbstractFileMonitor, and AbstractDictionary. Your job is to create two classes the first class should be named FileManager, the second class should be named Dictionary. The FileManager will implement the interfaces FileTextReader and FileTextWriter and extend the clas AbstractFileMonitor. Your class signature would look something like the following: public class FileManager extends AbstractFileMonitor implements FileTextReader, FileTextWriter{... The constructor signature of the FileManager should look like the following:...
7. What are abstract classes and interfaces in Java? What are they used for, and what...
7. What are abstract classes and interfaces in Java? What are they used for, and what are they comprised of? Clearly explain the difference between the two.
(Java) Please describe how API's can be created using abstract classes, interfaces and regular classes.
(Java) Please describe how API's can be created using abstract classes, interfaces and regular classes.
What are abstract classes? What are interfaces? What is the difference?
What are abstract classes? What are interfaces? What is the difference?
What are similarities and differences between abstract classes and interfaces? What are the default modifiers of...
What are similarities and differences between abstract classes and interfaces? What are the default modifiers of their methods and variables? What are allowed modifiers of their methods and variables? Essay Question
*JAVA* For this assignment you have been given two classes, a Main.java and a Coin.java. The...
*JAVA* For this assignment you have been given two classes, a Main.java and a Coin.java. The coin class represents a coin. Any object made from it will have a 1) name, 2) weight and 3) value. As of now, the instance variables in Coin.java are all public, and the main function is calling these variables directly for the one coin made in it. Your goal is to enforce information hiding principles in this project. Take Coin.java, make all instance variables...
Java assignment, abstract class, inheritance, and polymorphism. these are the following following classes: Animal (abstract) Has...
Java assignment, abstract class, inheritance, and polymorphism. these are the following following classes: Animal (abstract) Has a name property (string) Has a speech property (string) Has a constructor that takes two arguments, the name and the speech It has getSpeech() and setSpeech(speech) It has getName and setName(name) It has a method speak() that prints the name of the animal and the speech. o Example output: Tom says meow. Mouse Inherits the Animal class Has a constructor takes a name and...
This program focuses on programming with Java Collections classes. You will implement a module that finds...
This program focuses on programming with Java Collections classes. You will implement a module that finds a simplified Levenshtein distance between two words represented by strings. Your program will need support files LevenDistanceFinder.Java, dictionary.txt, while you will be implementing your code in the LevenDistanceFinder.java file. INSTRUCTIONS The Levenshtein distance, named for it's creator Vladimir Levenshtein, is a measure of the distance between two words. The edit distance between two strings is the minimum number of operations that are needed to...
Chapter 9 Programming Project (Inheritance, Abstract Class/Methods, Overriding Methods) -For all classes, you need to provide...
Chapter 9 Programming Project (Inheritance, Abstract Class/Methods, Overriding Methods) -For all classes, you need to provide the accessor and mutator methods for all instance variables, and provide/override the toString methods. -Create a Customer class that has the attributes of name and age. Provide a method named importanceLevel. Based on the requirements below, I would make this method abstract. -Extend Customer to two subclasses: FlightCustomer, and RetailCustomer -FlightCustomer attributes: ticketPrice, seatNumber (The seat number should be a randomly generated number between...
Make a class diagram (static structure with classes, interfaces and their relationship). It should include classes,...
Make a class diagram (static structure with classes, interfaces and their relationship). It should include classes, major attributes, major methods, class associations and multiplicities. The details of the project and its functional requirements are: Develop a sentiment analysis system for product rating. It is an e-commerce web application. The main objective of this sentiment analysis system is to understand the hidden sentiments of customers in feedback and comments and analyze their product rating patterns. When registered customers (they can create...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT