Our Feeds

Sunday, 27 July 2014

Ajith KP

Create a file compressor in Java

          It is not a tutorial. But its to share a source code of a Java application which for compressing files into ZIP archive. The line by line explanations are given in the source code.

          Download Netbeans Project File: http://downloads.ziddu.com/download/23930727/FileZip.zip.html


/*
 *  []
 *  []
 *  []
 *  [] ----> WwW.TerminalCoders.BlogSpot.DE <----
 *  []
 *  []
 *  []
 */
package filezip;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class FileZip extends JFrame {
        JButton btn = new JButton("OPEN");
        JTextArea area = new JTextArea();
        JPanel pnl = new JPanel(new GridLayout(1,1));
        JScrollPane pane = new JScrollPane();
    FileZip()
    {
        super("FILE ZIP - AJITH KP"); // Title
        setLayout(new BorderLayout()); // Set Layout to BorderLayout
        area.setEditable(false); // Textarea field cannot edit
        area.add(pane); // Adding scroll bar to Textarea
        area.setForeground(Color.black); // Textarea foreground is Black
        area.setBackground(Color.yellow); // Textarea backgrond is Yellow
        area.setFont(new Font("Times New Roman", Font.BOLD, 15)); // Textarea font is Time New Roman, Bold & size is 15
        pnl.add(btn); // Add button to panel
        add(pnl, BorderLayout.NORTH); // Add panel to Frame
        add(area, BorderLayout.CENTER); // Add Textarea to Frame
        btn.addActionListener(new ActionListener() // Button click capture
        {
            @Override
            public void actionPerformed(ActionEvent e) {
                area.setText("");
                showDlg();
            }            
        });
    }
    void showDlg()
    {     
        JFileChooser c = new JFileChooser(); // File chooser
        c.setFileSelectionMode(JFileChooser.FILES_ONLY); // Can select files only
        c.setMultiSelectionEnabled(true); // Multi selection is enabled
        int res = c.showOpenDialog(c); // Get result of file dialog
        if(res==JFileChooser.CANCEL_OPTION) // If you click cancel or closed the dialog
        {
            return;
        }
        File[] fls = c.getSelectedFiles(); // Else
        if(fls[0].toString().equals("")) // If you didn't select any file
        {
            return;
        }
        for(int i=0;i<fls.length;i++) // Else
        {
            area.setText(area.getText()+"Added:\t\t"+fls[i].getName()+"\n");
        }
        try {
            zipFile(fls); // Calling function zipFile
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileZip.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FileZip.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    void zipFile(File[] file) throws FileNotFoundException, IOException
    {
        int num = file.length; // Number of files you selected
        FileInputStream in[] = new FileInputStream[num]; // FileInputStream array
        File f2 = new File(file[0].getParent()); // Get the name of parent directory
        for(int i=0;i<num;i++)
        {
            in[i] = new FileInputStream(file[i]);
        }
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file[0].getParent()+"\\"+f2.getName()+".zip")); // Setting zip archive name
        for(int i=0; i<num; i++)
        {
            out.putNextEntry(new ZipEntry(file[i].getName())); // Adding files to zip archive
        }
        for(int i=0; i<num; i++) // Compressing each files you selected
        {
            byte[] b = new byte[1024];
            int count;
            while ((count = in[i].read(b)) > 0) {
                System.out.println();
                out.write(b, 0, count);
            }
        }
        for(int i=0; i<num;i++)
            in[i].close();
        out.close();
        area.setText(area.getText()+"\n\nFiles Zipped Successfully: "+f2.getName()+".zip");
    }
    public static void main(String[] args) throws FileNotFoundException, IOException {
        FileZip z = new FileZip();
        z.setSize(700, 500);
        z.setVisible(true);
        z.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}