简易版WinZip

 lsgZip.java

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.JOptionPane;

/**
 * 作者:李 世贵
 * JDK: 1.6
 * 来源: http://blog.csdn.net/lishigui
 * 欢迎转接,请保留作者和来源,谢谢!
 * 2008-9-28 上午09:49:06
 * 
 */

public class lsgZip extends JFrame{
    
     private static final long serialVersionUID = 1L;
     private int r=0;
     private int[] selectTableRow;
     private byte[] b=new byte[4096];
     private File file = null;
     private JTable table = null;
     private ZipEntry zipEntry = null;
     private JLabel labStatus = new JLabel();
     private String[] zipEntryInfo = new String[3];
     private MyTable defaultModel = null;
     private FileInputStream in = null;
     private ZipOutputStream zipfile;
     private JFileChooser filechooser = new JFileChooser();
     private String[] tableFields = {"文件名","路径","文件大小"};
     private FileFilter filter = new FileNameExtensionFilter("zip file","zip");
     public lsgZip() {
        super("李世贵简易版WinZip");
        Container container = getContentPane();
        container.setLayout(new BorderLayout());
        JMenuBarEven action = new JMenuBarEven();
        String[] emnuName ={"文件(F)@" + (int)'F', "操作(O)@" + (int)'O', "帮助(H)@" + (int)'H'};
        String[][]itemName = {{"新建(N)@" + (int)'N', "打开(O)@" + (int)'O', "退出(Q)@" + (int)'Q'}, {"添加(A)@" + (int)'A', "删除(D)@" + (int)'D', "解压(E)@" + (int)'E'}, {"手册(S)@" + (int)'S', "关于(A)@" + (int)'A'}};
        String[] name = {"把文件添加到压缩文件中", "解压压缩文件", "删除文件", "退出"}; 
        String[] image = {"image/Add.JPG", "image/Extract.JPG", "image/Delete.JPG", "image/Exit.JPG"};
        String[] text = {"添加", "解压", "删除", "退出"};
        
        this.setJMenuBar(createJMenuBar(emnuName, itemName, action));
        defaultModel = new MyTable(null, tableFields);
        table = new JTable(defaultModel);
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        table.addMouseListener(new MouseAdapter(){
            public void mouseReleased(MouseEvent e){
                selectTableRow = table.getSelectedRows();
            }
        });
        
        this.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                try {
                    if(zipfile != null){
                        zipfile.close();
                    }
                } catch (IOException e1) {
                }
                System.exit(0);
            }
        });
        
        container.add(createJToolBar(name, image, null, action), BorderLayout.NORTH);
        container.add(new JScrollPane(table), BorderLayout.CENTER);
        container.add(createStatusbar(), BorderLayout.SOUTH);
        Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
        
        this.setLocation((int)(screensize.getWidth()-300)/2, (int)(screensize.getHeight()-400)/2);
        setSize(300,400);
        setVisible(true);
    }
    //创建JMnuBar
    private JMenuBar createJMenuBar(String[] menuName, String[][] itemName, ActionListener action) {
        JMenuBar bar = new JMenuBar();
        JMenu[] menu = new JMenu[menuName.length];
        for(int i = 0; i < menuName.length; i++){
            if(menuName[i].split("@").length > 1){
                menu[i] = new JMenu(menuName[i].split("@")[0]);
                menu[i].setMnemonic(Integer.parseInt(menuName[i].split("@")[1]));
            }else{
                menu[i] = new JMenu(menuName[i]);
            }
            JMenuItem[] item = new JMenuItem[itemName[i].length];
            for(int j = 0; j < itemName[i].length; j++){
                if(itemName[i][j].split("@").length > 1){
                    item[j] = new JMenuItem(itemName[i][j].split("@")[0],Integer.parseInt(itemName[i][j].split("@")[1]));
                }else{
                    item[j] = new JMenuItem(itemName[i][j]);
                }
                item[j].addActionListener(action);
                menu[i].add(item[j]);
            }
            bar.add(menu[i]);
        }
        return bar;
        
    }
    //创建JToolBar
    private JToolBar createJToolBar(String[] name, String[] image, String[] text,ActionListener action){
        JToolBar bar = new JToolBar();
        for(int i = 0; i < name.length; i++){
            JButton b = new JButton(new ImageIcon(this.getClass().getResource(image[i])));
            if(text!=null){
                b.setText(text[i]);
                b.setVerticalTextPosition(AbstractButton.BOTTOM);
                b.setHorizontalTextPosition(AbstractButton.CENTER);
            }
            if(name!=null){
                b.setToolTipText(name[i]);
            }
            b.addActionListener(action);
            bar.add(b);
        }
        return bar;
    }
    //创建Statusbar
    private JPanel createStatusbar(){
        JPanel statusbar = new JPanel();
        statusbar.setLayout(new FlowLayout(FlowLayout.LEADING));
        statusbar.add(labStatus);
        return statusbar;
    }
    //重写DefaultTableModel使它不能编辑
    class MyTable extends DefaultTableModel {
        public MyTable(Object[][] Info, String[] names){
            super(Info,names);
        }
       public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
       }     
    }
    //侦听JMenuBar和JToolBar事件
    class JMenuBarEven implements ActionListener{

        public void actionPerformed(ActionEvent e) {
            //处理"新建"事件
            if(e.getActionCommand().equals("新建(N)")){
                newFile();
            }
            //处理"打开"事件
            if(e.getActionCommand().equals("打开(O)")){
                openFile();
            }
            //处理"退出"事件
            if(e.getActionCommand().equals("退出(Q)")){
                if(zipfile != null){
                    try {
                        zipfile.close();
                    } catch (IOException e1) {}
                }
                lsgZip.this.dispose();
                System.exit(0);
            }
            //处理"添加"事件
            if(e.getActionCommand().equals("添加(A)")){
                if(zipfile == null ){
                    newFile();
                    addFile();
                }else{
                    addFile();
                }
            }
            //处理"删除"事件
            if(e.getActionCommand().equals("删除(D)")){
                if(selectTableRow != null){
                    r = selectTableRow.length;
                    for(int i= 0; i < r; i++){
                        defaultModel.removeRow(selectTableRow[r-i-1]);
                        table.validate();
                    }
                    if(r > 0){
                        delFile();
                    }
                    r = 0;
                }
            }
            //处理"解压"事件
            if(e.getActionCommand().equals("解压(E)")){
                if(selectTableRow != null ){
                    if(selectTableRow.length > 0 ){
                        unzip();
                    }
                }
            }
            //处理"手册"事件
            if(e.getActionCommand().equals("手册(S)")){
                new helpDialog(lsgZip.this,"手册",false);
            }
            //处理"关于"事件
            if(e.getActionCommand().equals("关于(A)")){
                new aboutDialog(lsgZip.this,"关于",true);
                
            }
            //处理"JToolBar"事件
            if(e.getActionCommand().equals("")){
                JButton button = (JButton)e.getSource();
                if(button.getToolTipText().equals("把文件添加到压缩文件中")){
                    if(zipfile == null ){
                        newFile();
                        addFile();
                    }else{
                        addFile();
                    }
                }
                if(button.getToolTipText().equals("解压压缩文件")){
                    if(selectTableRow != null ){
                        if(selectTableRow.length > 0 ){
                            unzip();
                        }
                    }
                }
                if(button.getToolTipText().equals("删除文件")){
                    if(selectTableRow != null){
                        r = selectTableRow.length;
                        for(int i= 0; i < r; i++){
                            defaultModel.removeRow(selectTableRow[r-i-1]);
                            table.validate();
                        }
                        if(r > 0){
                            delFile();
                        }
                        r = 0;
                    }
                }
                if(button.getToolTipText().equals("退出")){
                    if(zipfile != null){
                        try {
                            zipfile.close();
                        } catch (IOException e1) {}
                    }
                    lsgZip.this.dispose();
                    System.exit(0);
                }
            }
        }
    }
    //新建处理
    private void newFile(){
        try{
            filechooser.setFileFilter(filter);
            filechooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            filechooser.setSelectedFile(new File("lsg.zip"));
            int result = filechooser.showDialog(lsgZip.this, "新建压缩文件");
            
            if ( result != JFileChooser.CANCEL_OPTION ){
                File newfile = filechooser.getSelectedFile(); 
                if(newfile.exists()){
                    result = JOptionPane.showConfirmDialog(lsgZip.this, "文件已存在,是否覆盖现有的文件", "提示", JOptionPane.YES_NO_OPTION);
                    if(result == JOptionPane.NO_OPTION){
                        newFile();
                    }
                    if(result == JOptionPane.YES_OPTION){
                        if(zipfile != null){
                            zipfile.close();
                            removeTableRow();
                        }
                        file = newfile;
                        zipfile = new ZipOutputStream(new FileOutputStream(file));
                    }
                }else{
                    if(filechooser.getSelectedFile() != null){
                        file = filechooser.getSelectedFile();
                        if(zipfile != null){
                            zipfile.close();
                            removeTableRow();
                        }
                        zipfile = new ZipOutputStream(new FileOutputStream(file));
                    }
                    
                }
            }
        } catch (FileNotFoundException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        }
    }
    //打开处理
    private void openFile(){
        try {
            filechooser.setFileFilter(filter);
            filechooser.setSelectedFile(null);
            filechooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int result = filechooser.showDialog(lsgZip.this, "打开压缩文件");
            if ( result != JFileChooser.CANCEL_OPTION ){
                File openfile = filechooser.getSelectedFile();
                if(openfile != null){
                    startopen(openfile);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //开始执行打开处理
    private void startopen(File openfile) throws IOException{
        file = openfile;
        if(zipfile != null){
            try{
                zipfile.close();
            }catch(Exception e){}
        }
        removeTableRow();
        openfile = new File(file.getParent() + "/lsg.tem");
        if(openfile.exists()){
            openfile.delete();
        }
        file.renameTo(openfile);
        while(!openfile.exists()){
            file.renameTo(openfile);
        }
        zipfile = new ZipOutputStream(new FileOutputStream(file));
        ZipInputStream zipin = new ZipInputStream(new FileInputStream(openfile));
        zipEntry = zipin.getNextEntry();
        while(zipEntry != null){
            zipfile.putNextEntry(zipEntry);
            while((r = zipin.read(b, 0, 4096)) > -1){
                zipfile.write(b, 0, r);
            }
            getEntryInfo(zipEntry);
            zipEntry = zipin.getNextEntry();
        }
        zipin.close();
        openfile.delete();
    }
    //添加处理
    private void addFile(){
        try{
            filechooser.setFileFilter(null);
            filechooser.setSelectedFile(null);
            filechooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            int result = filechooser.showDialog(lsgZip.this, "添加文件到压缩文件中");
            if(result == JFileChooser.CANCEL_OPTION){
                return;
            }
            File files = filechooser.getSelectedFile();
            zipfile.setMethod(ZipOutputStream.DEFLATED);
            if(files.isDirectory()){
                 Visitor(files, files.getName(), zipfile);
            }else{
                zipEntry = new ZipEntry(files.getName());
                zipEntry.setSize(files.length());
                zipEntry.setTime(new Date().getTime());
                zipfile.putNextEntry(zipEntry); 
                in = new FileInputStream(files); 
                while((r = in.read(b,0,4096)) > 0){ 
                    zipfile.write(b,0,r); 
                } 
                getEntryInfo(zipEntry); 
                in.close(); 
                zipfile.closeEntry();
            }
        } catch (FileNotFoundException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        }
    }
    
    //删除文件处理
    private void delFile(){
        try {
            File delfile = null;
            if(selectTableRow.length > 0){
                if(zipfile != null){
                    try{
                        zipfile.finish();
                        zipfile.close();
                    }catch(Exception e){}
                }
                delfile = new File(file.getParent()+"/lsg.tem");
                delfile.delete();
                file.renameTo(delfile);
                zipfile = new ZipOutputStream(new FileOutputStream(file));
                ZipFile filein = new ZipFile(delfile);
                InputStream in = null;
                for(int i = 0;i < table.getRowCount(); i++){
                    zipEntry = filein.getEntry(defaultModel.getValueAt(i, 1).toString());
                    zipfile.putNextEntry(zipEntry);
                    in = filein.getInputStream(zipEntry);
                    while((r = in.read(b, 0, 4096))>-1){
                        zipfile.write(b, 0, r);
                    }
                }
                if(in != null){
                    in.close();
                }
                filein.close();
                delfile.delete();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //解压处理
    private void unzip(){
        try{
            filechooser.setFileFilter(null);
            filechooser.setSelectedFile(null);
            filechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int result = filechooser.showDialog(lsgZip.this, "解压");
            if(result == JFileChooser.CANCEL_OPTION){
                return;
            }
            File outfile = filechooser.getSelectedFile();
            String filetring;
            if(outfile.toString().endsWith("//")){
                filetring = outfile.toString(); 
            }else{
                filetring = outfile.toString() + "//"; 
            }
            if(file != null){
                zipfile.close();
                ZipFile zipin = new ZipFile(file);
                File f;
                File parent;
                InputStream in;
                FileOutputStream out = null;
                for(int i = 0; i < selectTableRow.length; i++){
                    zipEntry = new ZipEntry(table.getValueAt(selectTableRow[i], 1).toString());
                    f = new File(filetring + zipEntry.toString());
                    parent = new File(f.getParent());
                    if(!parent.exists()){
                        parent.mkdirs();
                    }
                    in = zipin.getInputStream(zipEntry);
                    out = new FileOutputStream(f);
                    while((r = in.read(b, 0, 4096)) > -1){
                        out.write(b, 0, r);
                    }
                    in.close();
                    out.close();
                }
                zipin.close();
                File openfile = new File(file.toString());
                startopen(openfile);
            }
            
        } catch (FileNotFoundException e) { 
             
            e.printStackTrace(); 
        } catch (IOException e) { 
           
            e.printStackTrace(); 
        }
    }
    //将文件写到压缩文件
    private void Visitor(File directory, String entry, ZipOutputStream zipfile){
        try{
            File file = null;
            String[] fileList = directory.list();
            for(int i = 0; i < fileList.length; i++){
                file = new File(directory.toString() + "/" + fileList[i]);
                if(file.isDirectory()){
                     Visitor(file, entry + "/" + file.getName(), zipfile);
                }else{
                    zipEntry = new ZipEntry(entry + "/" + file.getName());
                    zipEntry.setSize(file.length());
                    zipEntry.setTime(new Date().getTime());
                    zipfile.putNextEntry(zipEntry); 
                    in=new FileInputStream(file); 
                    while((r=in.read(b,0,4096))>0){ 
                        zipfile.write(b,0,r); 
                    } 
                    getEntryInfo(zipEntry);
                    in.close(); 
                    zipfile.closeEntry();
                }
            }
        } catch (FileNotFoundException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
    }
    //在Entry的信息插入table中显示
    private void getEntryInfo(ZipEntry entry){
        File file = null;
        file = new File(entry.toString());
        zipEntryInfo[0] = file.getName();
        zipEntryInfo[1] = entry.toString();
        if(entry.getSize()==-1){
            zipEntryInfo[2] = "未知";
        }else{
            zipEntryInfo[2] = entry.getSize() / 1024 + "." + entry.getSize() % 1024 + "K";
        }
        defaultModel.addRow(zipEntryInfo);  
        table.validate();
        this.validate();
    }
    //删除表中所有的数据
    private void removeTableRow(){
        while(defaultModel.getRowCount()>0){
            defaultModel.removeRow(0);
            table.validate();
        }       
    }
    
    public static void main(String[] args) {
        new lsgZip();

    }

}

 helpDialog.java

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Frame;
import javax.swing.JDialog;
import javax.swing.JLabel;

public class helpDialog extends JDialog {
    private static final long serialVersionUID = 1L;
    public helpDialog(Frame arg0, String arg1, boolean arg2) {
        super(arg0, arg1, arg2);
        Container container = getContentPane();
        container.setLayout(new FlowLayout(FlowLayout.LEFT));
        JLabel label = new JLabel();
        label.setText(
            "<html><h2 align=center><FONT color=blue>手册  </FONT></h2>" +
            "<p><FONT color=blue>新建压缩文件:</FONT>" +
            "<br>在菜单栏中选择"文件"->"新建",在弹出" +
            "<br>对话框中选择"新建压缩文件"的保存路径,然" +
            "<br>后输入"新建压缩文件"的文件名,默认的文件" +
            "<br>名是lag.zip.新建好压缩文件后就可以往"新" +
            "<br>建压缩文件"中添加多个文件夹或文件"+
            "<P><FONT color=blue>打开压缩文件:</FONT>" +
            "<br>在菜单栏中选择"文件"->"打开",在弹出对" +
            "<br>话框中选择要打开的压缩文件,单击打开,就可以" +
            "<br>打开压缩文件"+
            "<p><FONT color=blue>添加文件到压缩文件:</FONT>" +
            "<br>在菜单栏中选择"操作"->"添加"或者单击工" +
            "<br>具栏中的"添加",在弹出对话框中选择文件或文件" +
            "<br>夹添加到当前的压缩文件"+
            "<p><FONT color=blue>删除压缩文件中的文件:</FONT>" +
            "<br>在表中选择一个或者多个文件,然后单击菜单栏中选" +
            "<br>择"操作"->"删除"或者单击工具栏中的"删除"," +
            "<br>就可以删除选择中的文件了"+
            "<p><FONT color=blue>解压压缩文件:</FONT>" +
            "<br>在表中选择一个或者多个文件,然后单击菜单栏中选择" +
            "<br>"操作"->"解压"或者单击工具栏中的"解压"," +
            "<br>在弹出对话框中选择保存解压文件的路径,就可" +
            "<br>以解压选择中的文件了"+
            "<p><FONT color=blue>退出程序:</FONT>" +
            "<br>单击右上角的关闭,在菜单栏中选择"文件"->" +
            "<br>"退出",单击工具栏中的"退出"都能退出程序"+"</html>"  
        );
        this.setResizable(false);
        container.add(label);
        setSize(390,550);
        setVisible(true);
    }
}

aboutDialog.java

import java.awt.Container;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.Window;

import javax.swing.JDialog;
import javax.swing.JLabel;


public class aboutDialog extends JDialog {
    public aboutDialog(Frame arg0, String arg1, boolean arg2) {
        super(arg0, arg1, arg2);
        Container container = getContentPane();
        container.setLayout(new FlowLayout(FlowLayout.LEFT));
        JLabel label = new JLabel();
        label.setText("<html><h3 align=center><FONT color=blue>   李世贵简易版WinZip</FONT></h3>" +
                            "<b align=left><FONT color=blue> Version:</FONT>1.0</b>" +
                            "<br><b align=left> <FONT color=blue>Author:</FONT>   lishigui</b></html>");
        container.add(label);
        this.setResizable(false);
        setSize(180,150);
        setVisible(true);
    }
}

该程序在我的资源网可以下载,欢迎你下载使用哦!
我的资源网地址是:http://lishigui.download.csdn.net/
程序运行的界面如下:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值