UNB/ CS/ David Bremner/ teaching/ cs1083/ java/ PBM4.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;


public class PBM4 {
    private int[][] bits;
    private int rows,columns;
    PBM4(String fileName) throws ImageFormatException, FileNotFoundException, IOException{
        BufferedReader in = new BufferedReader(new FileReader(fileName));
        String first=in.readLine();
        if (!first.equals("P1"))
            throw new ImageFormatException("Format error");
        String second = in.readLine();
        String[] parts= second.split(" ");
        columns=Integer.parseInt(parts[0]);
        rows=Integer.parseInt(parts[1]);
        bits=new int[rows][columns];
        for (int i=0; i< rows; i++){
            for (int j=0; j<columns; j++) {
                int nextChar = in.read();
                while (nextChar == ' ' || nextChar == '\n') {
                    nextChar = in.read();
                }
                bits[i][j]=nextChar-'0';
            }
        }
    }
    public String toString(){
        String result="";
        for (int i=0; i< rows; i++){
            String row="";
            for (int j=0; j<columns; j++){
                if (bits[i][j]==1)
                    row += "*";
                else
                    row += " ";
            }
            result += row+"\n";
        }
        return result;

    }

    public static void main(String [] args) throws ImageFormatException, FileNotFoundException, IOException{

        long startTime = System.nanoTime();
        PBM4 pbm = new PBM4(args[0]);
        long readTime = System.nanoTime();
        System.out.println("time to read " + (readTime-startTime)/1e6 + "ms");

        String str = pbm.toString();
        long stringTime = System.nanoTime();
        System.out.println("time to string " + (stringTime-readTime)/1e6 + "ms");


        BufferedWriter out = new BufferedWriter(new FileWriter(args[1]));
        out.write(str,0,str.length());
        out.close();
        long wroteTime = System.nanoTime();

        System.out.println("time to write " + (wroteTime-stringTime)/1e6 + "ms");
    }
}
//@keywords: array, 2D array, bitmap, file, image processing