// CSE 143, Winter 2009, Marty Stepp // A TallyDownloader object is an extension of a Downloader that also // echoes the bytes read to the console and keeps a tally of how many occurrences // of each character it found in the file. // This class demonstrates inheritance to add functionality to a class. // (It also has a Map that uses the Character wrapper type to wrap char values.) import java.io.*; import java.net.*; import java.util.*; public class TallyDownloader extends Downloader { // Constructs a new tally downloader to read from the URL with the given // text representation, such as "http://www.google.com/". // Throws a MalformedURLException if this is not a valid URL. public TallyDownloader(String urlString) throws MalformedURLException { super(urlString); // call Downloader constructor } // Reads from this downloader's URL and writes its contents to the given file. // Also prints the file contents and prints a tally of how many of each // character were found in the file (using a Map). // Throws an IOException if there is any error while reading/writing data. public void download(String targetFileName) throws IOException { super.download(targetFileName); Map counts = new TreeMap(); FileInputStream in = new FileInputStream(targetFileName); while (true) { int n = in.read(); if (n == -1) { break; } char ch = (char) n; if (counts.containsKey(ch)) { counts.put(ch, counts.get(ch) + 1); } else { counts.put(ch, 1); } System.out.print(ch); } in.close(); System.out.println(counts); // print map of character -> int counters } }