Question

In: Computer Science

write a program in Java that can take a given text file and then compress it...

write a program in Java that can take a given text file and then compress it with Huffman coding due 20 october 2020

Huffman coding can be used to “zip” a text file to save space. You are required to write a program in Java that can take a given text file and then compress it with Huffman coding. Your program should be able to decompress the zipped files as well [4 marks]. In addition, show percentage gain in data compression i.e., how much space is saved [2 marks].

Compare the effectiveness of your Huffman code with 7-zip and WinZip softwares. You will get a bonus mark if you enhance the existing Huffman code somehow to have a better file compressor. It can also be published as a research article.

Correct Implementation: read about FileOutputStream, FileInputStream, FileReader etc to read/write to a binary file. You may use Integer.parseInt(huffmanCodeAsString,2) to store encoded Huffman code into a binary file. Huffman encoding should convert a text file to a binary file then decoding should convert the binary file back to a text file.

Please provide all java code. Be clear as possible when you paste the code so that it works in my pc  

Use netbeans IDE.

Solutions

Expert Solution

1. DECODER


import java.io.*;
import FileBitIO.*;


public class CHuffmanDecoder implements huffmanSignature{

        
        private String fileName,outputFilename;
        private String[] hCodes = new String[MAXCHARS];
        private int distinctChars = 0;
        private long fileLen=0,outputFilelen;
        
        private FileOutputStream outf;
        private String gSummary;

        
        public CHuffmanDecoder(){
                loadFile("","");
                }
        public CHuffmanDecoder(String txt){
                loadFile(txt);
                }
        public CHuffmanDecoder(String txt,String txt2){
                loadFile(txt,txt2);
                }
                
        public void loadFile(String txt){
                fileName = txt;
                outputFilename = stripExtension(txt,strExtension);
                gSummary = "";
                }
        public void loadFile(String txt,String txt2){
                fileName = txt;
                outputFilename = txt2;
                gSummary = "";
                }
        String stripExtension(String ff,String ext){
                ff = ff.toLowerCase();
                if(ff.endsWith(ext.toLowerCase())){
                        return ff.substring(0,ff.length()-ext.length());
                        }
                return "_" + ff;
                }
                
        public boolean decodeFile() throws Exception{
                
                
                if(fileName.length() == 0) return false;
                
                for(int i=0;i<MAXCHARS;i++) hCodes[i] = "";
                long i;
                CFileBitReader fin = new CFileBitReader(fileName);
                fileLen = fin.available();

                String buf;
                buf = fin.getBytes(hSignature.length());
                
                if(!buf.equals(hSignature)) return false;
                outputFilelen = Long.parseLong(fin.getBits(32),2);
                distinctChars = Integer.parseInt(fin.getBits(8),2) + 1;
                gSummary  += ("Compressed File Size : "+ fileLen + "\n");
                gSummary  += ("Original   File Size : "+ outputFilelen + "\n");
                gSummary  += ("Distinct   Chars     : "+ distinctChars + "\n");
                for(i=0;i<distinctChars;i++){
                        
                        int ch = Integer.parseInt(fin.getBits(8),2);
                        int len = Integer.parseInt(leftPadder(fin.getBits(5),8),2);
                        hCodes[ch] = fin.getBits(len);
                        //System.out.println((char)ch + " : "  + hCodes[ch]);
                        }
                
                try{
                
                outf = new FileOutputStream(outputFilename);
                i = 0;
                int k;
                int ch;
                
                while(i < outputFilelen){    
                                buf = "";
                                for(k=0;k<32;k++){
                                        buf += fin.getBit();
                                        ch  = findCodeword(buf);
                                                if(ch > -1){
                                                        outf.write((char)ch);
                                                        buf = "";
                                                        i++;
                                                        break;
                                                }
                                        }
                                if(k >=32 ) throw new Exception("Corrupted File!");
                                
                        }
                
                outf.close();
                return true;
                
                }catch(Exception e){
                        throw e;
                }
 

                }
                
        int findCodeword(String cw){
                int ret = -1;
                for(int i=0;i<MAXCHARS;i++){
                        if(hCodes[i] != "" && cw.equals(hCodes[i])){
                                ret = i;
                                break;
                        }
                        }
                        return ret;
                }

        
        String leftPadder(String txt,int n){
                while(txt.length() < n )
                        txt =  "0" + txt;
                return txt;
                }
        
        String rightPadder(String txt,int n){
                while(txt.length() < n )
                        txt += "0";
                return txt;
                }
                
        public String getSummary(){
                return gSummary;
                }
        
}



2. ENCODER


import java.io.*;
import FileBitIO.CFileBitWriter;


public class CHuffmanEncoder implements huffmanSignature{
        
        
        private String fileName,outputFilename;
        private HuffmanNode root = null;
        private long[] freq  = new long[MAXCHARS];
        private String[] hCodes = new String[MAXCHARS];
        private int distinctChars = 0;
        private long fileLen=0,outputFilelen;
        private FileInputStream fin;
        private BufferedInputStream in; 
        private String gSummary;

        
        void resetFrequency(){
                for(int i=0;i<MAXCHARS;i++)
                freq[i] = 0;
                
                distinctChars = 0;
                fileLen=0;
                gSummary ="";
                }
        
        public CHuffmanEncoder(){
                loadFile("","");
                }
        public CHuffmanEncoder(String txt){
                loadFile(txt);
                }
        public CHuffmanEncoder(String txt,String txt2){
                loadFile(txt,txt2);
                }
                
        public void loadFile(String txt){
                fileName = txt;
                outputFilename = txt + strExtension;
                resetFrequency();
                }
        public void loadFile(String txt,String txt2){
                fileName = txt;
                outputFilename = txt2;
                resetFrequency();
                }
        public boolean encodeFile() throws Exception{
                
                if(fileName.length() == 0) return false;
                try{
                fin = new FileInputStream(fileName);
                in = new BufferedInputStream(fin);
                }catch(Exception e){ throw e; }
                
                //Frequency Analysis
                try
                {
                        fileLen = in.available();
                        if(fileLen == 0) throw new Exception("File is Empty!");
                        gSummary += ("Original File Size : "+ fileLen + "\n");
                        
                        long i=0;

                        in.mark((int)fileLen);
                        distinctChars = 0;
                        
                        while (i < fileLen)
                        {               
                                int ch = in.read();                     
                                i++;
                                if(freq[ch] == 0) distinctChars++;
                                freq[ch]++;
                                
                        }
                        in.reset();                     
                }
                catch(IOException e)
                {
                        throw e;
                        //return false;
                }
                gSummary += ("Distinct Chars " + distinctChars + "\n");
                /*
                System.out.println("distinct Chars " + distinctChars);
                 //debug
                for(int i=0;i<MAXCHARS;i++){
                        if(freq[i] > 0)
                        System.out.println(i + ")" + (char)i + " : " + freq[i]);
                }
                */
                
                CPriorityQueue  cpq = new CPriorityQueue (distinctChars+1);
                
                int count  = 0 ;
                for(int i=0;i<MAXCHARS;i++){
                        if(freq[i] > 0){
                                count ++;
                                //System.out.println("ch = " + (char)i + " : freq = " + freq[i]);
                                HuffmanNode np = new HuffmanNode(freq[i],(char)i,null,null);
                                cpq.Enqueue(np);
                                }
                }
                
                //cpq.displayQ();
                
                HuffmanNode low1,low2;
                
                while(cpq.totalNodes() > 1){
                        low1 = cpq.Dequeue();
                        low2 = cpq.Dequeue();
                        if(low1 == null || low2 == null) { throw new Exception("PQueue Error!"); }
                        HuffmanNode intermediate = new HuffmanNode((low1.freq+low2.freq),(char)0,low1,low2);
                        if(intermediate == null) { throw new Exception("Not Enough Memory!"); }
                        cpq.Enqueue(intermediate);

                }
                
                //cpq.displayQ();
                //root = new HuffmanNode();
                root = cpq.Dequeue();
                buildHuffmanCodes(root,"");
                
                for(int i=0;i<MAXCHARS;i++) hCodes[i] = "";
                getHuffmanCodes(root);
                
                /*
                //debug         
                for(int i=0;i<MAXCHARS;i++){
                if(hCodes[i] != ""){ 
                System.out.println(i + " : " + hCodes[i]);
                }
                }
                */
                
                CFileBitWriter hFile = new CFileBitWriter(outputFilename);
                
                hFile.putString(hSignature);
                String buf;
                buf = leftPadder(Long.toString(fileLen,2),32); //fileLen
                hFile.putBits(buf);
                buf = leftPadder(Integer.toString(distinctChars-1,2),8); //No of Encoded Chars
                hFile.putBits(buf);
                
                for(int i=0;i<MAXCHARS;i++){
                        if(hCodes[i].length() != 0){
                                buf = leftPadder(Integer.toString(i,2),8);
                                hFile.putBits(buf);
                                buf = leftPadder(Integer.toString(hCodes[i].length(),2),5);
                                hFile.putBits(buf);
                                hFile.putBits(hCodes[i]);
                                }
                        }
                
                long lcount = 0;
                while(lcount < fileLen){
                        int ch = in.read();
                        hFile.putBits(hCodes[(int)ch]);
                        lcount++;
                }
                hFile.closeFile();
                outputFilelen =  new File(outputFilename).length();
                float cratio = (float)(((outputFilelen)*100)/(float)fileLen);
                gSummary += ("Compressed File Size : " + outputFilelen + "\n");
                gSummary += ("Compression Ratio : " + cratio + "%" + "\n");
                return true;
                
                }
        
        void buildHuffmanCodes(HuffmanNode parentNode,String parentCode){

                parentNode.huffCode = parentCode;
                if(parentNode.left != null)
                        buildHuffmanCodes(parentNode.left,parentCode + "0");
                
                if(parentNode.right != null)
                        buildHuffmanCodes(parentNode.right,parentCode + "1");
                }
        
        void getHuffmanCodes(HuffmanNode parentNode){
                
                if(parentNode == null) return;
                
                int asciiCode = (int)parentNode.ch;
                if(parentNode.left == null || parentNode.right == null)
                hCodes[asciiCode] = parentNode.huffCode;
                
                if(parentNode.left != null ) getHuffmanCodes(parentNode.left);
                if(parentNode.right != null ) getHuffmanCodes(parentNode.right);
        }
        
        String leftPadder(String txt,int n){
                while(txt.length() < n )
                        txt =  "0" + txt;
                return txt;
                }
        
        String rightPadder(String txt,int n){
                while(txt.length() < n )
                        txt += "0";
                return txt;
                }
                
        public String getSummary(){
                return gSummary;
                }
}


3. Priority_Queue


class CPriorityQueue{
        final int DEFAULTMAX = 256;
        
        HuffmanNode [] nodes;
        int capacity,total;
        
        public CPriorityQueue(){
                capacity = DEFAULTMAX;
                total = 0;
                nodes = new HuffmanNode[capacity];
        }
        public CPriorityQueue(int max){
                capacity = max;
                total = 0;
                nodes = new HuffmanNode[capacity];
                
        }
        
        public boolean Enqueue(HuffmanNode np){
                
                if(isFull()) return false;
                
                if(isEmpty()){ //first element?
                        nodes[total++] = np;
                        return true;
                }
                int i = total-1,pos;
                while(i >= 0){
                        if(nodes[i].freq < np.freq){
                                break;
                                }
                        i--;
                        }
                pos = total-1;
                while(pos >= i+1){
                        nodes[pos+1] = nodes[pos];
                        pos--;
                        }
                nodes[i+1] = np;
                total++;
                return true;
        }
        
        public HuffmanNode Dequeue(){
                
                if(isEmpty()) return null;
                HuffmanNode ret = nodes[0];
                total--;
                for(int i = 0;i<total;i++)
                nodes[i] = nodes[i+1];
                return ret;
                }
        
        public boolean isEmpty(){
                return (total == 0);
                }
        
        public boolean isFull(){
                return (total == capacity);
                }
                
        public int totalNodes(){
                return total;
                }
                
        //debug
        public void displayQ(){
        for(int i=0;i<total;i++){
                System.out.println("Q" + i + ") " + nodes[i].ch + " : " + nodes[i].freq);
                }       
                
                }
        
}

4. huffmanSignature


public interface huffmanSignature {
        final String hSignature = "SHE";
        final int MAXCHARS = 256;
        final String strExtension = ".huf";

    
}

5. GPh


public class Gph extends javax.swing.JFrame implements GphGuiConstants {
    
    /** Creates new form Gph */
    public Gph() {
        
       
        initComponents();
        
       //  buttonGroup1.setSelected(jRadioButton1,true);
    }
    
    
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jFileChooser1 = new javax.swing.JFileChooser();
        buttonGroup1 = new javax.swing.ButtonGroup();
        jFrame1 = new javax.swing.JFrame();
        jPanel3 = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();

        jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFileChooser1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Compression-Decompression");
        setBackground(new java.awt.Color(255, 0, 0));
        setForeground(new java.awt.Color(51, 0, 255));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jPanel3.setBackground(new java.awt.Color(102, 0, 0));
        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 440, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 481, Short.MAX_VALUE)
        );

        jTabbedPane1.setBackground(new java.awt.Color(204, 204, 204));
        jTabbedPane1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTabbedPane1MouseClicked(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(255, 255, 204));
        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel2.setText("Source");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel3.setText("Destination");

        jButton1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jButton1.setText("Browse");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Tahoma", 1, 11));
        jButton2.setText("Browse");
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel4.setText("Algorithms");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "LZW", "GZIP", "HUFFMAN", "RUNLENGTH" }));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel5.setText("Procedure");

        jRadioButton1.setBackground(new java.awt.Color(255, 255, 204));
        buttonGroup1.add(jRadioButton1);
        jRadioButton1.setFont(new java.awt.Font("Tahoma", 1, 12));
        jRadioButton1.setText("Compress");
        jRadioButton1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        jRadioButton1.setMargin(new java.awt.Insets(0, 0, 0, 0));
        jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton1ActionPerformed(evt);
            }
        });

        jRadioButton2.setBackground(new java.awt.Color(255, 255, 204));
        buttonGroup1.add(jRadioButton2);
        jRadioButton2.setFont(new java.awt.Font("Tahoma", 1, 12));
        jRadioButton2.setText("Decompress");
        jRadioButton2.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        jRadioButton2.setMargin(new java.awt.Insets(0, 0, 0, 0));
        jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton2ActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton3.setFont(new java.awt.Font("Tahoma", 1, 11));
        jButton3.setText("Ok");
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton3MouseClicked(evt);
            }
        });

        jButton4.setFont(new java.awt.Font("Tahoma", 1, 11));
        jButton4.setText("Clear");
        jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton4MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(154, 154, 154)
                        .addComponent(jButton3)
                        .addGap(40, 40, 40)
                        .addComponent(jButton4))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5)
                            .addComponent(jLabel3))
                        .addGap(14, 14, 14)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                                .addComponent(jButton2))
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE)
                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                            .addComponent(jRadioButton1)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(jRadioButton2)))
                                    .addGap(17, 17, 17)
                                    .addComponent(jButton1))
                                .addComponent(jScrollPane1)))))
                .addContainerGap(48, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(145, 145, 145)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(25, 25, 25)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jRadioButton1)
                    .addComponent(jRadioButton2)
                    .addComponent(jLabel5))
                .addGap(33, 33, 33)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(31, 31, 31)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jButton2))
                .addGap(15, 15, 15)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton4)
                    .addComponent(jButton3))
                .addContainerGap())
        );
        jTabbedPane1.addTab("Compression-Decompression", jPanel1);

        jPanel2.setBackground(new java.awt.Color(255, 255, 204));
        jLabel6.setIcon(new javax.swing.ImageIcon("C:\\Documents and Settings\\admin\\Desktop\\wingph14 may\\src\\GPH.JPG"));

        jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GPH.JPG")));

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 386, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 395, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 337, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addContainerGap(22, Short.MAX_VALUE))
        );
        jTabbedPane1.addTab("About", jPanel2);

        jLabel1.setBackground(new java.awt.Color(0, 0, 0));
        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel1.setForeground(new java.awt.Color(255, 255, 204));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("WinGPH");
        jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jLabel1.getAccessibleContext().setAccessibleParent(jFrame1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 420, Short.MAX_VALUE)
                .addGap(20, 20, 20))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(175, Short.MAX_VALUE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(91, 91, 91))
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 393, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(49, Short.MAX_VALUE))
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed
suggestDestination();// TODO add your handling code here:
    }//GEN-LAST:event_jRadioButton2ActionPerformed

    private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
suggestDestination();// TODO add your handling code here:
    }//GEN-LAST:event_jRadioButton1ActionPerformed

    private void jFileChooser1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFileChooser1ActionPerformed
// TODO add your handling code here:
    }//GEN-LAST:event_jFileChooser1ActionPerformed

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        int returnVal = jFileChooser1.showOpenDialog(this);
        
        if (returnVal == jFileChooser1.APPROVE_OPTION) {
            jTextField1.setText("");
            jTextField2.setText("");
            File file = jFileChooser1.getSelectedFile();
            
            if(file.exists()){
                log("Source : [" +  file.getName() + "]");
                jTextField1.setText(file.getPath());
                suggestDestination();
            }
        }
// TODO add your handling code here:
    }//GEN-LAST:event_jButton1MouseClicked

    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked
        int returnVal = jFileChooser1.showSaveDialog(this);
        
        if (returnVal == jFileChooser1.APPROVE_OPTION) {
            jTextField2.setText("");
            File file = jFileChooser1.getSelectedFile();
            log("Destination : [" + file.getName() + "]");
            jTextField2.setText(file.getPath());
            
            if(jRadioButton1.isSelected()){
                        jTextField2.setText(jTextField2.getText() + extensionArray[algoSelected]);
                    }else
                    if(jTextField1.getText().endsWith(extensionArray[algoSelected])){
                        String buf = jTextField2.getText().substring(0,jTextField2.getText().lastIndexOf(extensionArray[algoSelected]));
                        System.out.println(jTextField1.getText().lastIndexOf(extensionArray[algoSelected]));
                        jTextField2.setText(buf);
                         
                        
                        
                    }else{
                         jTextField2.setText(jTextField1.getText() + extensionArray[algoSelected]);
                        }
        }
        
// TODO add your handling code here:
    }//GEN-LAST:event_jButton2MouseClicked

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        log("Algorithm Selected : [" + jComboBox1.getSelectedItem() + "]");
        algoSelected = jComboBox1.getSelectedIndex();
        suggestDestination();
        
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked
        
        String temp;
        boolean flag=false;
        if(jTextField1.getText().length() == 0 || jTextField2.getText().length() == 0){
            log("Fill all Fields!");
            return;
        }
        
        
        GphWorkingDlg dlg = new GphWorkingDlg(jFrame1);
        int mode = (jRadioButton1.isSelected())? COMPRESS : DECOMPRESS;
        int j = 0,k;
       // String algos;
        if(mode==33)
        {
                        temp =jTextField1.getText();
                        
                        for(int i=0;i<4;i++)
                        {
                        if(temp.endsWith(extensionArray[i]))
                        {   j=i;
                            flag=true;
                           // algos=extensionArray[i];
                        }
                        }
                        if(!flag)
                        {  
                            log("Error : choose compressed file  " );
                            return;
                        }
                        k=jComboBox1.getSelectedIndex();
                        if(k!=j){
                            jTextArea1.setText("");
                            log("Error :Choose correct algorithm");}
        }  
        // System.out.println(algoSelected);
        dlg.doWork(jTextField1.getText(),jTextField2.getText(),mode,algoSelected);
        log(dlg.getSummary());
        
// TODO add your handling code here:
    }//GEN-LAST:event_jButton3MouseClicked

    private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton4MouseClicked
        clearDetails();
        jRadioButton1.setSelected(true);
// TODO add your handling code here:
    }//GEN-LAST:event_jButton4MouseClicked

    private void jTabbedPane1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTabbedPane1MouseClicked
// TODO add your handling code here:
    }//GEN-LAST:event_jTabbedPane1MouseClicked

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
// TODO add your handling code here:
    }//GEN-LAST:event_formWindowActivated
        void log(String stuff){
                if(jTextArea1.getDocument().getLength() > 3000) jTextArea1.setText(REFRESH);
                jTextArea1.append("\n" + stuff);
                jTextArea1.setCaretPosition(jTextArea1.getDocument().getLength());
                
                }
        
                void clearDetails(){
                
                jTextArea1.setText(REFRESH);
                jTextField1.setText("");
                jTextField2.setText("");
                }
                
                void suggestDestination(){
                if(jTextField1.getText().length() == 0) return ;
                //System.out.println(algoSelected);
                if(jRadioButton1.isSelected()){
                        jTextField2.setText(jTextField1.getText() + extensionArray[algoSelected]);
                    }else
                    if(jTextField1.getText().endsWith(extensionArray[algoSelected])){
                        String buf = jTextField1.getText().substring(0,jTextField1.getText().lastIndexOf(extensionArray[algoSelected]));
                        System.out.println(jTextField1.getText().lastIndexOf(extensionArray[algoSelected]));
                        jTextField2.setText(buf);
                         
                        
                        
                    }else{
                         jTextField2.setText(jTextField1.getText() + extensionArray[algoSelected]);
                        }
                
                
                }
  
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Gph().setVisible(true);
            }
        });
    }
        final String REFRESH = "\t   ----- Status -----";
        private int algoSelected = COMP_LZW;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration//GEN-END:variables
    
}

6. List


package wingph;


public interface GphGuiConstants {
        String[] algorithmNamesArray = {                "Huffman Compression",
                                                                                        
                                                                                        
                                                                                        };

        String[] extensionArray = {                                                     
                                                                                        
                                                                                        ".huf",
                                                                                        
                                                                                                                                                        
                                                                                        
                                                                                        };
      
        
        final int COMP_HUFFMAN = 0;
        
       
        final int COMPRESS = 32;
        final int DECOMPRESS = 33;
        
        
        
}

7. Gph workingDlg



package wingph;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

import CHuffmanCompressor.*;

import CRLECompressor.*;
import CLZWCompressor.*;
import CGZipCompressor.*;

public class GphWorkingDlg extends JDialog implements ActionListener,GphGuiConstants {
    
    
        private JFrame owner;
        private JProgressBar prgBar;
        private JButton btnCancel; 
        private JLabel lblNote;
        private String gSummary = "";
        private String iFilename,oFilename;
        private boolean bCompress = false;
        private int algoSelected;
        
        
        void centerWindow(){
                Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
        
        setLocation((screensize.width / 2) - (getSize().width / 2),
                    (screensize.height / 2) - (getSize().height / 2));
                }
    
    /** Creates a new instance of GphWorkingDlg */
    public GphWorkingDlg(JFrame parent) {
        
                super(parent,true);
                owner = parent;
                setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                
                addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent we) {
                        //setTitle("Thwarted user attempt to close window.");
                }
                });

                
                setSize(300,120);
                centerWindow();
                buildDlg();
                setResizable(false);
                btnCancel.addActionListener(this);
                //setVisible(true);
    }
    
    void buildConstraints(GridBagConstraints gbc, int gx, int gy,
                        int gw, int gh, int wx, int wy) {
                gbc.fill = GridBagConstraints.HORIZONTAL;
                gbc.gridx = gx;
                gbc.gridy = gy;
                gbc.gridwidth = gw;
                gbc.gridheight = gh;
                gbc.weightx = wx;
                gbc.weighty = wy;
                
                }
                
        void buildDlg(){
                GridBagLayout gridbag = new GridBagLayout();
                GridBagConstraints constraints = new GridBagConstraints();
                constraints.anchor = GridBagConstraints.CENTER;
                setLayout(gridbag);
                prgBar = new JProgressBar();
                prgBar.setSize(100,30);
                prgBar.setStringPainted(false);
                prgBar.setIndeterminate(true);
                btnCancel = new JButton("Cancel");
                lblNote  = new JLabel("hahah",JLabel.CENTER);
                
                constraints.insets = new Insets(3,3,3,3);  
                
                buildConstraints(constraints,1,0,2,1,50,30);
                gridbag.setConstraints(lblNote  ,constraints) ;
                add(lblNote);
                buildConstraints(constraints,0,1,4,1,100,40);
                gridbag.setConstraints(prgBar,constraints) ;
                add(prgBar);
                buildConstraints(constraints,1,2,2,1,50,30);
                constraints.fill = GridBagConstraints.NONE;
                gridbag.setConstraints(btnCancel ,constraints) ;
                add(btnCancel );
                
                }
                
        void doWork(String inputFilename,String outputFilename,int mode,int algorithm){
                String buf;
               // boolean flag=false;
                File infile = new File(inputFilename);
                
                //chk if file exists
                if(!infile.exists()){
                        gSummary += "File Does not Exits!\n";
                        return;
                        }
                bCompress = (mode == COMPRESS);
                if(bCompress )
                        lblNote.setText("Compressing " + infile.getName());
                else
                    {
                        lblNote.setText("Decompressing " + infile.getName());
                       
                 }   
                setTitle(lblNote.getText());
        
                final int falgo = algorithm;
                iFilename = inputFilename;
                oFilename = outputFilename;
                gSummary = "";

                //Create Thread for Compress/Decompress
                final Runnable closeRunner = new Runnable(){
                        public void run(){
                                setVisible(false);
                                dispose();
                        }

                        };
System.out.println(falgo);
                Runnable workingThread = new Runnable(){
                        public void run(){
                                try{
                                        boolean success = false;
                                        switch(falgo){
                                                
                                                case COMP_HUFFMAN : 
                                                        if(bCompress){
                                                                CHuffmanEncoder he = new        CHuffmanEncoder(iFilename,oFilename);
                                                                success = he.encodeFile();
                                                                gSummary += he.getSummary();
                                                                
                                                        }else{
                                                                CHuffmanDecoder hde = new       CHuffmanDecoder(iFilename,oFilename);
                                                                success = hde.decodeFile();
                                                                gSummary += hde.getSummary();
                                                        }
                                                        break;
                                                
                                                case COMP_GZIP : 
                                                        if(bCompress){
                                                                CGZipEncoder gze = new  CGZipEncoder(iFilename,oFilename);
                                                                success  = gze.encodeFile();
                                                                gSummary += gze.getSummary();
                                                                
                                                        }else{
                                                                CGZipDecoder gzde = new CGZipDecoder(iFilename,oFilename);
                                                                success = gzde.decodeFile();
                                                                gSummary += gzde.getSummary();
                                                        }
                                                        break;
                                        
                                                case COMP_RLE:
                                                        if(bCompress){
                                                                CRLEEncoder rle = new   CRLEEncoder(iFilename,oFilename);
                                                                success = rle.encodeFile();
                                                                gSummary += rle.getSummary();
                                                                
                                                        }else{
                                                                CRLEDecoder unrle = new CRLEDecoder(iFilename,oFilename);
                                                                success = unrle.decodeFile();
                                                                gSummary += unrle.getSummary();
                                                        }
                                                        break; 

                                                case COMP_LZW:
                                                        if(bCompress){
                                                                CLZWEncoder lzwe = new  CLZWEncoder(iFilename,oFilename);
                                                                success = lzwe.encodeFile();
                                                                gSummary += lzwe.getSummary();
                                                                
                                                        }else{
                                                                CLZWDecoder lzwd = new  CLZWDecoder(iFilename,oFilename);
                                                                success = lzwd.decodeFile();
                                                                gSummary += lzwd.getSummary();
                                                        }
                                                        break;

                                        }
                                        
                                        }catch(Exception e){
                                        gSummary += e.getMessage();
                                        }
                                        
                                        try{
                                                SwingUtilities.invokeAndWait(closeRunner );
                                        }catch(Exception e){
                                                gSummary += "\n" + e.getMessage();
                                                }
                                
                                }
                        };//working thread
                        
                        
                Thread work = new Thread(workingThread);
                work.start();
                
                setVisible(true);
                
                
                }

    public void actionPerformed(ActionEvent e) { //called only when cancel is pressed
        //Object obj = e.getSource();
        dispose();
                }
                
        public String getSummary(){
                if(gSummary.length() > 0){
                String line = "----------------------------------------------";
                return line + "\n" + gSummary + line;
                }else return "";
                
                }
    
}

8. MAin.java

public class Main {
    
    /** Creates a new instance of Main */
    public Main() {
          
    }
          /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Gph().setVisible(true);
    }
            
          });
       
    }
    
}

    





Related Solutions

Write a java program: Write a program that creates a text file. Write to the file...
Write a java program: Write a program that creates a text file. Write to the file three lines each line having a person's name. In the same program Append to the file one line of  'Kean University'.  In the same program then Read the file and print the four lines without lines between.
Please write a java program to write to a text file and to read from a...
Please write a java program to write to a text file and to read from a text file.
You are given a text file containing a short text. Write a program that 1. Reads...
You are given a text file containing a short text. Write a program that 1. Reads a given text file : shortText.txt 2. Display the text as it is 3. Prints the number of lines 4. Prints the occurences of each letter that appears in the text. [uppercase and lowercase letter is treated the same]. 5. Prints the total number of special characters appear in the text. 6. Thedisplayofstep3,4and5aboveshouldbesaveinanoutputfile:occurencesText.txt write it in C++ programing Language
In JAVA Write a brief program that writes your name to a file in text format...
In JAVA Write a brief program that writes your name to a file in text format and then reads it back. Use the PrintWriter and Scanner classes.
I need to write a java program (in eclipse) that will read my text file and...
I need to write a java program (in eclipse) that will read my text file and replace specific placeholders with information provided in a second text file. For this assignment I am given a text file and I must replace <N>, <A>, <G>, with the information in the second file. For example the information can be John 22 male, and the template will then be modified and saved into a new file or files (because there will be multiple entries...
In Java language. Write a brief program that writes your name to a file in text...
In Java language. Write a brief program that writes your name to a file in text format and then reads it back. Use the PrintWriter and Scanner classes.
Write a JAVA program that reads a text file into RAM efficiently, takes a regular expression...
Write a JAVA program that reads a text file into RAM efficiently, takes a regular expression from the user, and then prints every line that matches the RE.
WRITE A JAVA PROGRAM TO IMPLEMENT THE CONCEPT OF INDEX (Create index in text file) full...
WRITE A JAVA PROGRAM TO IMPLEMENT THE CONCEPT OF INDEX (Create index in text file) full code
Write a program in Java that reads an input text file (named: input.txt) that has several...
Write a program in Java that reads an input text file (named: input.txt) that has several lines of text and put those line in a data structure, make all lowercase letters to uppercase and all uppercase letters to lowercase and writes the new lines to a file (named: output.txt).
Write a C program that can search for a string within a text file, replace it...
Write a C program that can search for a string within a text file, replace it with another string and put results in a new file.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT