In: Computer Science
Implement the following method take takes the name of an ASCII text file and displays the frequency of each character in the file. (6 pts)
public static void CountCharacters(String filename)
{
...
}
// Main provided for testing
public static void main(String args[])
{
CountCharacters("testfile.dat");
}
Output should be in the following format:
ASCII CODE - COUNTS
10 - 1
66 - 2
104 - 1
import java.nio.file.*;
import java.util.*;
public class Ans {
public static void CountCharacters(String filename)
{
System.out.println("ASCII CODE - COUNTS");
String data = "";
// Read file into String
try {
data = new String(Files.readAllBytes(Paths.get(filename)));
}catch(Exception e) {
e.printStackTrace();
}
// Map to store frequency counts
HashMap<Integer, Integer> map = new HashMap<Integer,
Integer>();
for(int i=0;i<data.length();i++) {
int k = data.charAt(i);
// Map already contains key
if(map.containsKey(k)) {
int val = map.get(k);
map.put(k,val+1);
}
// New key in map
else
map.put(k, 1);
}
// Display keys in sorted order
TreeMap<Integer, Integer> sorted = new
TreeMap<>();
sorted.putAll(map);
for (Map.Entry<Integer, Integer> entry :
sorted.entrySet())
System.out.println(entry.getKey()+"\t"+entry.getValue());
}
public static void main(String args[])
{
CountCharacters("testfile.dat");
}
}