Question

In: Computer Science

Read previously created binary file using ObjectInputStream Create an appropriate instance of HashMap from Java library...

  1. Read previously created binary file using ObjectInputStream
  2. Create an appropriate instance of HashMap from Java library
  3. Populate the HashMap with data from binary file
  4. Display the information read in a user friendly format

Problem:

Given: Words.dat – a binary file consisting of all the words in War and Peace

Goal: Read the words in from the binary file and figure out how many times each word appears in the file. Display the results to the user.

Use a HashMap with the word as a key (String) and an Integer as the value.   For each word, first check to see if it already exists in the Map. If not, add the word as key with a value of 1 for the Integer value.

If it does, get the current value and increment by 1 – replace the old key,value with the new key, value.

After all the words are processed and the HashMap is complete. Iterate through the Hash map and display the results in a user -friendly fashion. Tell me which option you chose in the Assignment box when you submit the homework

Display Options: (Choose one not all)

  1. Create an easy to read table and print to the console. Hint: Use tabs (/t) (values are not from file)

Example:

Word                     Count

A                             190

Apple                    6

Etc

  1. Display on a Java FX Gui – use ListView for the Words and click to see count

C. Create a text file with the data formatted similar to the console

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

/**
* This file is intended to show how the binary file words.dat was created

*This is not intended to be used only to
* demonstrate how the file was written so it can be read properly

*cjohns25
*/
public class CreateBinaryFile
{

   public static void main(String[] args)
   {
       // step 1 - read in all the words from war and peace into an arrayList
       ArrayList words = new ArrayList();
       Scanner in;
       try
       {
           in = new Scanner(new File("war-and-peace.txt"));

           // Use any characters other than a-z or A-Z as delimiters
           in.useDelimiter("[^a-zA-Z]+");
           while (in.hasNext())
           {
               words.add(in.next().toLowerCase());
           }
           in.close();
       } catch (FileNotFoundException e)
       {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }

       // write to words.dat in binary format
       // open a binary file with ObjectOutputStream for writing
       try
       {
           // Create an output stream for file words.data
           ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("words.dat", true));

           // Write arrayList to the object output stream one string at a time
           for (String w : words)
           {
               output.writeObject(w);
           }

           output.close();

       } catch (Exception e)
       {
           e.printStackTrace(); // provide this to see where problem occurred
           System.out.println("Problem encountered writing file"); // provide this for user
       }

   }
}

*My CODE*

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.HashMap;


public class HashMapWords {
public static void main(String[] args) throws Exception {

HashMap<String, Integer> map = new HashMap<String, Integer>();
try (ObjectInputStream datFile = new ObjectInputStream(new FileInputStream("words.dat"))) {

while (true) {
try {
String key = datFile.readUTF();
if (!map.containsKey(key)) {
map.put(key, 0);
}
map.put(key, map.get(key) + 1);
} catch (Exception ex) {
break;
}
}
}

System.out.println("Word\t\tCount");

for (String key : map.keySet()) {
System.out.println(key + "\t\t" + map.get(key));
}
}

}

*OUTPUT*

Word Count

*HAVING TROUBLE MAKING THIS WORK REALLY NEED SOME HELP, TELL ME WHAT IM DOING WRONG. THANK YOU FOR THE HELP *

Solutions

Expert Solution

The error was on only one line namely ==> String key = datFile.readUTF();==> this doesnot work because UTF-8 is a text to binary encoding which means conversion of text to binary will succeed ...but conversion from binary to string may fail ...So UTF function will not be used here ...Now since Object is being written in binary file ...So use readObject function to read the object and typecast it with String object...

i.e    String key = (String)datFile.readObject(); //read objects from binary file and typecast to required Object

Attaching the code snippet and screenshot ..

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package hashmapwords;

/**
 *
 * @author vijay
 */
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.HashMap;


public class HashMapWords {
public static void main(String[] args) throws Exception {

HashMap<String, Integer> map = new HashMap<String, Integer>();
try (ObjectInputStream datFile = new ObjectInputStream(new FileInputStream("words.dat"))) {

while (true) {
try {
    String key = (String)datFile.readObject(); //read objects from binary file and typecast to required Object 

if (!map.containsKey(key)) {
map.put(key, 0);
}
map.put(key, map.get(key) + 1);
} catch (Exception ex) {
break;
}
}
}

System.out.println("Word\t\tCount");

for (String key : map.keySet()) {
System.out.println(key + "\t\t" + map.get(key));
}
}

}

Screenshots ==>input.txt is the file which was converted to binary format file words.dat


Related Solutions

Using Java create an application that will read a tab-delimited file that displays the MLB standings...
Using Java create an application that will read a tab-delimited file that displays the MLB standings Below: League AL East Tampa Bay 37 20 NY Yankees 32 24 Toronto 29 27 Baltimore 23 33 Boston 22 34 League AL Central Minnesota 35 22 Chi White Sox 34 23 Cleveland 33 24 Kansas City 23 33 Detroit 22 32 League AL West Oakland 34 21 Houston 28 28 LA Angels 26 31 Seattle 25 31 Texas 19 37 League NL East...
How to read and print all contents in a binary file using a Binary Search Tree...
How to read and print all contents in a binary file using a Binary Search Tree inorder traversal in C. Additionally, how to search using a Binary Search Tree to display the specific Athlete and his/her information. An example would be a sports record binary file that consist of name of athlete, height , weight, championships won. Athlete: Michael Jordan Height: 6’6” Weight : 205 lbs Championships won: 6 =================== Athlete: LeBron James Height: 6’8” Weight: 250 lbs Championships won:...
Using JAVA The following code is able to read integers from a file that is called...
Using JAVA The following code is able to read integers from a file that is called "start.ppm" onto a 3d array called "startImage". Implement the code by being able to read from another file (make up any file name) and save the data onto another 3d array lets say you call that array "finalImage". The purpose of this will be to add both arrays and then get the average Save the average onto a separte 3darray,lets say you call it...
Using JAVA The following code is able to read integers from a file that is called...
Using JAVA The following code is able to read integers from a file that is called "start.ppm" onto a 3d array called "startImage". Implement the code by being able to read from another file (make up any file name) and save the data onto another 3d array lets say you call that array "finalImage". The purpose of this will be to add both arrays and then get the average Save the average onto a separte 3darray,lets say you call it...
using the header: #include <pthread.h> // This is a header file for a Read/Right Lock Library....
using the header: #include <pthread.h> // This is a header file for a Read/Right Lock Library. Your C code //SHOULD access your routines using these exact function // prototypes typedef struct RW_lock_s { } RW_lock_t; void RW_lock_init(RW_lock_t *lock); /* This routine should be called on a pointer to a struct variable of RW_lock_t to initialize it and ready it for use. */ void RW_read_lock(RW_lock_t *lock); /* This routine should be called at the beginning of a READER critical section */...
Create a c file to read from an existing file one character at a time and...
Create a c file to read from an existing file one character at a time and print that character to the console Create a c file to read a character from the standard input and write it to a file. please help me
Write a java program that can create, read, and append a file. Assume that all data...
Write a java program that can create, read, and append a file. Assume that all data written to the file are string type. One driver class and a class that contains the methods. The program should have three methods as follows: CreateFile - only creating a file. Once it create a file successfully, it notifies to the user that it creates a file successfully. ReadingFile - It reads a contents of the file. This method only allow to read a...
Please write a java program to write to a text file and to read from a...
Please write a java program to write to a text file and to read from a text file.
JAVA Assignment: Project File Processing. Write a program that will read in from input file one...
JAVA Assignment: Project File Processing. Write a program that will read in from input file one line at a time until end of file and output the number of words in the line and the number of occurrences of each letter. Define a word to be any string of letters that is delimited at each end by either whitespace, a period, a comma or the beginning or end of the line. You can assume that the input consists entirely of...
Using java, I need to make a program that reverses a file. The program will read...
Using java, I need to make a program that reverses a file. The program will read the text file character by character, push the characters into a stack, then pop the characters into a new text file (with each character in revers order) EX: Hello World                       eyB       Bye            becomes    dlroW olleH I have the Stack and the Linked List part of this taken care of, I'm just having trouble connecting the stack and the text file together and...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT