Java大作业之压缩解压缩

编写软件,实现文件和目录的压缩与解压缩。具体包括UI实现,多选文件或目录,指定压缩位置和解压缩位置,以及自己设计其他功能。

软件的图形界面

view.java

package view;

import function.Compress;
import function.Decompression;
import  java.awt.Button;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.*;
import java.text.DecimalFormat;
import java.util.zip.ZipOutputStream;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.*;

public class View extends JFrame{
    private  static final long serialVersionUID=1L;
    private JPanel contentPane;
    private JTextField textField;
    private JTextField textField2;
    private JTextField textField3;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try{
                    View frame=new View();
                    frame.setVisible(true);
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    public View(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100,100,450,342);
        contentPane=new JPanel();
        contentPane.setBorder(new EmptyBorder(5,5,5,5));
        setContentPane(contentPane);
        contentPane.setLayout(null);


        textField = new JTextField();
        textField.setBounds(97, 23, 184, 24);
        contentPane.add(textField);
        textField.setColumns(10);

        JButton Button2 = new JButton("压缩");
        Button2.setBounds(65, 228, 113, 27);
        contentPane.add(Button2);

        JButton Button3 = new JButton("解压");
        Button3.setBounds(245, 228, 113, 27);
        contentPane.add(Button3);

        JLabel Label3 = new JLabel("压缩路径");
        Label3.setBounds(28, 57, 72, 18);
        contentPane.add(Label3);

        textField2 = new JTextField();
        textField2.setBounds(97, 54, 184, 24);
        contentPane.add(textField2);
        textField2.setColumns(10);

        JLabel Label1 = new JLabel("文件路径");
        Label1.setBounds(28, 26, 72, 18);
        contentPane.add(Label1);

        JButton Button1 = new JButton("浏览");
        Button1.setBounds(295, 22, 72, 27);
        contentPane.add(Button1);

        textField = new JTextField();
        textField.setBounds(97, 23, 184, 24);
        contentPane.add(textField);
        textField.setColumns(10);

        JButton Button4 = new JButton("浏览");
        Button4.setBounds(295, 53, 72, 27);
        contentPane.add(Button4);

        JLabel lblNewLabel = new JLabel("解压路径");
        lblNewLabel.setBounds(28, 88, 72, 18);
        contentPane.add(lblNewLabel);

        textField3 = new JTextField();
        textField3.setBounds(97, 88, 184, 24);
        contentPane.add(textField3);
        textField3.setColumns(10);

        JButton Button5 = new JButton("浏览");
        Button5.setBounds(295, 84, 72, 27);
        contentPane.add(Button5);

        Button4.addActionListener(new ActionListener() {  //给按键添加监听器
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser  chooser=new JFileChooser();
                chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); //设置文件选择模式
                chooser.setMultiSelectionEnabled(true);  //设置多选
                int returnVal=chooser.showOpenDialog(new Button());
                System.out.println("returnVal="+returnVal);

                if(returnVal==JFileChooser.APPROVE_OPTION){
                    String filepath=chooser.getSelectedFile().getAbsolutePath();
                    System.out.println(filepath);
                    System.out.println("You chose to open this file: "+chooser.getSelectedFile().getName());
                    textField2.setText(filepath+"\\compress.zip");
                }
            }
        });

        Button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser=new JFileChooser();
                chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                chooser.setMultiSelectionEnabled(true);
                int returnVal=chooser.showOpenDialog(new Button());
                System.out.println("returnVal="+returnVal);

                if(returnVal==JFileChooser.APPROVE_OPTION){
                    String filepath=chooser.getSelectedFile().getAbsolutePath();
                    System.out.println(filepath);
                    System.out.println("You chose to open this file: "+chooser.getSelectedFile().getName());
                    textField.setText(filepath);
                }
            }
        });

        Button5.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser=new JFileChooser();
                chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                chooser.setMultiSelectionEnabled(true);
                int returnVal=chooser.showOpenDialog(new Button());
                System.out.println("returnVal="+returnVal);
                if(returnVal==JFileChooser.APPROVE_OPTION){
                    String filepath=chooser.getSelectedFile().getAbsolutePath();
                    System.out.println(filepath);
                    System.out.println("You chose to open this file: "+chooser.getSelectedFile().getName());
                    textField3.setText(filepath+"\\decompress");
                }
            }
        });

        Button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!textField.getText().equals("")) {
                    Compress compress = new Compress();
                    try {
                        FileOutputStream fos=new FileOutputStream(textField2.getText());
                        ZipOutputStream zos=new ZipOutputStream(fos);
                        File file=new File(textField.getText());
                        compress.compress(file,file.getName(),zos);
                        File file1 = new File(textField.getText());
                        File file2 = new File(textField2.getText());
                        //double num = (double) file2.length() / (double) file1.length();
                        //DecimalFormat df = new DecimalFormat("0.000%");
                        zos.close();
                        fos.close();
                        //String r = df.format(num);
                        JOptionPane.showMessageDialog(contentPane, "Compress success! Compressibility:" , "Success Prompt", 1);

                    } catch (Exception exception) {
                        JOptionPane.showMessageDialog(contentPane, "Compress failed, the file format does not support compression", "Failure Prompt", 1);
                        exception.printStackTrace();
                    }
                }
            }
        });

        Button3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(!textField.getText().equals("")){
                    Decompression d=new Decompression();
                    try {
                        d.decompress(textField.getText(),textField3.getText());
                        System.out.println("decompress success");
                        JOptionPane.showMessageDialog(contentPane,"Decompress success!");
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(contentPane,"Decompress failed!","Failure Prompt", 1);
                        throw new RuntimeException(ex);
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(contentPane,"Decompress failed!","Failure Prompt", 1);
                        throw new RuntimeException(ex);
                    }
                }
            }
        });


    }
}



zip压缩与解压缩

Compress.java

package function;
import java.io.*;
import java.util.zip.*;
public class Compress {

    public static void  compress(File srcFile,String desPath,ZipOutputStream zos) throws IOException {
        if (srcFile.isHidden()) {
            return;
        }
        if (srcFile.isDirectory()) {
            if (desPath.endsWith("/")) {
                zos.putNextEntry(new ZipEntry(desPath));
                zos.closeEntry();
            } else {
                zos.putNextEntry(new ZipEntry(desPath + "/"));
                zos.closeEntry();
            }
            File[] children = srcFile.listFiles();
            for (File childFile : children) {   //递归遍历所有文件
                compress(childFile, desPath + "/" + childFile.getName(), zos);
            }
            return;
        }
        FileInputStream fis = new FileInputStream(srcFile);
        ZipEntry zipEntry = new ZipEntry(desPath);
        zos.putNextEntry(zipEntry);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zos.write(bytes, 0, length);
        }
        fis.close();

    }

    public static void main(String[] args) throws IOException {
        String path="C:\\Users\\11757\\Desktop\\test\\test1";
        String destPath="C:\\Users\\11757\\Desktop\\test\\compression.zip";
        //待压缩的目录
        //压缩以后得到的文件路径compression.zip
        FileOutputStream fos = new FileOutputStream(destPath);
        ZipOutputStream zipOut = new ZipOutputStream(fos);
        File fileToZip = new File(path);
        compress(fileToZip, fileToZip.getName(), zipOut);
        zipOut.close();
        fos.close();
    }
}


Decompress.java

package function;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Decompression {
    public static void decompress(String path,String destPath) throws Exception {
        File srcFile=new File(path);
        if(!srcFile.exists())              //判断文件是否存在
            throw new Exception(srcFile.getPath()+" dosen't exist");
        ZipInputStream zin=new ZipInputStream(new FileInputStream(srcFile));
        ZipEntry entry=null;
        File file=null;
        while((entry=zin.getNextEntry())!=null){
            if(!entry.isDirectory()){           //判断是否为目录
                file=new File(destPath,entry.getName());
                if(!file.exists()){
                    new File(file.getParent()).mkdirs();
                }
                OutputStream out=new FileOutputStream(file);
                BufferedOutputStream bos=new BufferedOutputStream(out);
                int len=-1;
                byte[] buf=new byte[1024];
                while((len=zin.read(buf))!=-1){
                    bos.write(buf,0,len);
                }
                bos.close();
                out.close();
            }
        }

    }
    public static void main(String[] args) throws Exception {
        String source="C:\\Users\\11757\\Desktop\\test\\compression.zip";
        String dest="C:\\Users\\11757\\Desktop\\test\\decompression";
        decompress(source,dest);
    }
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

能饮一杯吴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值