Question

QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes...

QUESTION

The ReadFile class opens and reads a text file. The WriteFile class opens and writes to a file. Compile and run these programs.

There are several ways to read/write text files. The examples shown here are just one way of achieving this.

Look at the API for the BufferedReader class. The readline() method is a simple way to read the text file line by line. It returns null when the end of the file has been reached.

https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html

Look at the API for the PrintWriter class. Notice that we can print to a file just like we print to the terminal. There are overloaded print() and println() methods that print with or without adding a newline.

https://docs.oracle.com/javase/8/docs/api/java/io/PrintWriter.html

Using the ReadFile and WriteFile classes as a starting point, write a program in a file called Frequent.java, that reads all the contents of a file (the provided text.txt, for example) and finds the 10 most frequently used words.

Your program will read every line in the input file and record each word in the line. A word is a sequence of consecutive non-whitespace characters.

Note that the split() method in the String class will break up a string into words.

 String s = "the cat in the     hat   .";
 String[] words = s.split("\\s+");

Here, the input "\\s+" tell split() to split the string s by whitespace characters.

Use a dictionary (HashMap) to store the words. The keys should be your words and the values should be the frequency count. Each time you see a word that you have already seen, you will need to update the value for that work (that key).

How do you use a HashMap? The API gives you lots of information!

https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html

Once you have built your dictionary, you will need to extract all the key value pairs. You can, for example, use the keySet() method to obtain a set (use a Set for this; if you try to use HashSet you'll run into problems) of all the keys in the dictionary. You can then use this set to build list (ArrayList) of key-value pairs. You can use the helper class KeyValue for this if you wish. You can then sort the list using Collections.sort() since KeyValue implements comparable.

Once you have sorted the list, you write the last 10 (the 10 with the highest frequency) to a file called "best10.txt".

Note: Java provided a Map.Entry interface to help do this same thing (in place of the KeyValue class). Feel free to use this other approach for this problem.

package comp1406t5;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
import java.io.FileWriter;


public class WriteFile {

public static String filename = "output.txt";

public static void main(String[] args) {
try {
PrintWriter out;

// open file for writing
// (deleting current contents if the file already exists)
out = new PrintWriter(new FileWriter(filename));

// write to the file
for(int i=0; i<10; i+=1){
for(int j=0; j<20; j+=1){
if( Math.random() < 0.5 ){
out.print("/");
}else{
out.print("\\");
}
}
out.println();
}

// close the file
out.close();

} catch (FileNotFoundException e) {
System.out.println("Error: Cannot open file \"" + filename + "\" for writing.");
} catch (IOException e) {
System.out.println("Error: Cannot write to file \"" + filename + "\".");
}
}


}

package comp1406t5;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;

public class ReadFile {

public static String filename = "input.txt";

public static void main(String args[]) {
try {

BufferedReader in;

// open file
in = new BufferedReader(new FileReader(filename));

// read from file
String line = in.readLine();
while( line != null ){
System.out.println(line);
line = in.readLine();
}

// clse file
in.close();

} catch (FileNotFoundException e) {
System.out.println("Error: Cannot open file \"" + filename + "\" for reading");
} catch (IOException e) {
System.out.println("Error: Cannot read from file \"" + filename + "\"");
}
}
}

package comp1406t5;


public class KeyValue implements Comparable<KeyValue>{
public String key;
public Integer value;

public KeyValue(String k, Integer v){
key = k;
value = v;
}

@Override
public int compareTo(KeyValue other){
return value.compareTo(other.value);
}
@Override
public String toString(){
return key + ":" + value;
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

2* import java.io. BufferedReader; 10 11 public class Most FrequentWords { static Map<String, Integer> map = new HashMap<Stri

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class MostFrequentWords {
        static Map<String, Integer> map = new HashMap<String, Integer>(); 
        
        static void readFile(String fileName) throws IOException {
                BufferedReader reader = new BufferedReader(new FileReader(fileName));
                String line;

                while ((line = reader.readLine()) != null) {
                        // remove punctuation
                        String tokens[] = line.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
                        for(String token: tokens) {
                                token = token.trim();
                                map.put(token, map.getOrDefault(token, 0) + 1);
                        }
                }

                reader.close();
        }

        public static void main(String[] args) throws IOException {
                Scanner userInput = new Scanner(System.in);
                System.out.print("Enter file path : ");
                String fileName = userInput.next();
                
                // read file and populate hashmap
                readFile(fileName);
                
                ArrayList<String> keys = new ArrayList<>(map.keySet());
                keys.sort(new Comparator<String>() {
                        @Override
                        public int compare(String key1, String key2) {
                                return map.get(key2) - map.get(key1);
                        }
                        
                });
                
                int i = 0;
                for(String key: keys) {
                        if(i == 10) {
                                break;
                        }
                        Integer count = map.get(key);
                        System.out.println(String.format("%-20s%d", key, count));
                        i++;
                }
                
                // close scanner
                userInput.close();
        }

}


Hi. Please find the answer above.. In case of any doubts, you may ask in comments. You may upvote the answer if you feel i did a good work!

Add a comment
Know the answer?
Add Answer to:
QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Complete the code: package hw4; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.Scanner; /* * This...

    Complete the code: package hw4; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.Scanner; /* * This class is used by: * 1. FindSpacing.java * 2. FindSpacingDriver.java * 3. WordGame.java * 4. WordGameDriver.java */ public class WordGameHelperClass { /* * Returns true if an only the string s * is equal to one of the strings in dict. * Assumes dict is in alphabetical order. */ public static boolean inDictionary(String [] dict, String s) { // TODO Implement using binary search...

  • create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines....

    create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines. ** Each method below, including main, should handle (catch) any Exceptions that are thrown. ** ** If an Exception is thrown and caught, print the Exception's message to the command line. ** Write a complete Java method called checkWord that takes a String parameter called word, returns nothing, and is declared to throw an Exception of type Exception. In the method, check if the...

  • Complete the Java command line application. The application accepts a URL from the command line. This...

    Complete the Java command line application. The application accepts a URL from the command line. This application should then make a HTTP request to “GET” the HTML page for that URL, then print the HTTP header as well as the HTML for the page to the console. You must use the Java “socket” class to do all network I/O with the webserver. Yes, I’m aware this is on Stack Overflow, but you must understand how this works, as you will...

  • Using java socket programming rewrite the following program to handle multiple clients simultaneously (multi threaded programming)...

    Using java socket programming rewrite the following program to handle multiple clients simultaneously (multi threaded programming) import java.io.*; import java.net.*; public class WelcomeClient { public static void main(String[] args) throws IOException {    if (args.length != 2) { System.err.println( "Usage: java EchoClient <host name> <port number>"); System.exit(1); } String hostName = args[0]; int portNumber = Integer.parseInt(args[1]); try ( Socket kkSocket = new Socket(hostName, portNumber); PrintWriter out = new PrintWriter(kkSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(kkSocket.getInputStream())); ) { BufferedReader...

  • Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file...

    Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file doesn’t exist. You will process through the file skipping any text or real (double) numbers. You will print the max, min, sum, count, and average of the integers in the file. You will want to create test files that contain integers, doubles, and Strings. HINT: Use hasNextInt() method and while loop. You may also want to use Integer.MAX_VALUE and Integer.MIN_VALUE for the initialization of...

  • composed the following java code to read a string from a text file but receiving compiling...

    composed the following java code to read a string from a text file but receiving compiling errors. The text file is MyNumData.txt. Included the original java script that generated the output file. Shown also in the required output results after running the java program. I can't seem to search for the string and output the results. Any assistance will be greatly appreciated. import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class Main {   public static void main(String[] args) {     System.out.print("Enter the...

  • Please help me fix my errors. I would like to read and write the text file...

    Please help me fix my errors. I would like to read and write the text file in java. my function part do not have errors. below is my code import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.FileWriter; import java.io.IOException; public class LinkedList {    Node head;    class Node    {        int data;        Node next;       Node(int d)        {            data = d;            next = null;        }    }    void printMiddle()    {        Node slow_ptr...

  • Complete code and answer question in comments: Package hw4; import java.util.ArrayList; public c...

    Complete code and answer question in comments: Package hw4; import java.util.ArrayList; public class WordGame { /* * Returns all strings that appear * as a consecutive horizontal or vertical sequence of letters * (left-right, right-left, up-down, or down-up) * in the array board and also appear in dict. * Note that the same word may appear multiple times * on the board, and will then be multiple times in * the returned array. * * dict is assumed to be...

  • Ask the user for the name of a file and a word. Using the FileStats class,...

    Ask the user for the name of a file and a word. Using the FileStats class, show how many lines the file has and how many lines contain the text. Standard Input                 Files in the same directory romeo-and-juliet.txt the romeo-and-juliet.txt Required Output Enter a filename\n romeo-and-juliet.txt has 5268 lines\n Enter some text\n 1137 line(s) contain "the"\n Your Program's Output Enter a filename\n romeo-and-juliet.txt has 5268 lines\n Enter some text\n 553 line(s) contain "the"\n (Your output is too short.) My...

  • package Lab11; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Lab10 {    public...

    package Lab11; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Lab10 {    public static void main (String [] args)    {    // ============================================================    // Step 2. Declaring Variables You Need    // These constants are used to define 2D array and loop conditions    final int NUM_ROWS = 4;    final int NUM_COLS = 3;            String filename = "Input.txt";    // A String variable used to save the lines read from input...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT