In: Computer Science
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)
Example:
Word Count
A 190
Apple 6
Etc
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 *
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