Chapter 18 - Exercise 19

(2) Using BinaryFile and a Map, create a program that counts the occurrence of all the different bytes in a file.


BinaryFile.java



package com.ciaoshen.thinkinjava.chapter18;
import java.util.*;
import java.io.*;

public class BinaryFile {
    public static byte[] read(File bFile) throws IOException{
        BufferedInputStream bf = new BufferedInputStream(new FileInputStream(bFile));
        try {
            byte[] data = new byte[bf.available()];
            bf.read(data);
            return data;
        } finally {
            bf.close();
        }
    }
    public static byte[] read(String bFile) throws IOException {
        return read(new File(bFile).getAbsoluteFile());
    }
}


Exercise19.java



package com.ciaoshen.thinkinjava.chapter18;
import java.util.*;
import java.io.*;

public class Exercise19  {
    public static void main(String[] args) throws IOException{
        byte[] bytes=BinaryFile.read("/Users/Wei/java/com/ciaoshen/thinkinjava/chapter18/BinaryFile.java");
        Map<Byte,Integer> map=new HashMap<Byte,Integer>();
        for(int i=0;i<bytes.length;i++){
            byte b=bytes[i];
            if(map.containsKey(b)){
                map.put(b,map.get(b)+1);
            }else{
                map.put(b,1);
            }
        }
        System.out.println(map);
    }
}



Need Java Developers? Hire Me »

I know Java. Talk is cheap, watch my code.

I live in CANADA now.