search
HomeJavajavaTutorialExample of how to compress and decompress files in Java

Example of how to compress and decompress files in Java

Sep 22, 2017 am 11:43 AM
javacompressionUnzip

This article shares with you how to compress/decompress files in Java through example code. Friends who need it can refer to it

Compress/decompress files using java:


import java.io.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 
import java.util.zip.*; 
import javax.swing.*; 
//从压缩包中提取文件 
public class ZipExtractDemo extends JFrame{ 
  JFileChooser fileChooser; //文件选择器 
  JTextField jtfTarget; //待解压文件路径 
  JButton jbSelected; //选择文件按钮 
  JList files; //信息显示列表框 
  JButton jbExtract; //解压按钮 
  ZipFile zFile;  
  public ZipExtractDemo(){ 
    super("从压缩包中提取文件"); //调用父类构造函数 
    fileChooser=new JFileChooser(); //实例化组件 
    jtfTarget=new JTextField(13); 
    jbSelected=new JButton("选择"); 
    jbExtract=new JButton("解压"); 
    files=new JList(); 
    JPanel panel=new JPanel(); //实例化面板 
    panel.add(new JLabel("目标文件")); 
    panel.add(jtfTarget); //增加组件到面板上 
    panel.add(jbSelected); 
    panel.add(jbExtract); 
    JScrollPane jsp=new JScrollPane(files); 
    jsp.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); //设置边界 
    Container container=getContentPane(); //得以容器 
    container.add(panel,BorderLayout.NORTH); //增加组件到容器上 
    container.add(jsp,BorderLayout.CENTER); 
    jbSelected.addActionListener(new ActionListener(){ //文件选择按钮事件处理 
      public void actionPerformed(ActionEvent event) { 
        if (fileChooser.showOpenDialog(ZipExtractDemo.this)==JFileChooser.APPROVE_OPTION){ //弹出文件选择器,并判断是否点击了打开按钮 
          String fileName=fileChooser.getSelectedFile().getAbsolutePath();  //得到选择文件的绝对路径 
          jtfTarget.setText(fileName); //设置目标文件名 
          showFiles(); //显示压缩包内容 
      } 
      } 
    }); 
    jbExtract.addActionListener(new ActionListener(){  //解村文件按钮事件处理 
      public void actionPerformed(ActionEvent event) {  
          extractFile(files.getSelectedValue().toString()); //解压指定文件 
      } 
    }); 
    setSize(350,250);  //设置窗口尺寸 
    setVisible(true);  //设置窗口可视 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序 
  } 
  public void showFiles(){ 
    try{ 
    zFile=new ZipFile(jtfTarget.getText()); //得到压缩文件实例 
    ZipEntry entry; 
    Vector vec=new Vector(); //文件枚举 
      Enumeration enu=zFile.entries(); //得到压缩条目的枚举对象 
      while (enu.hasMoreElements()){ //依次枚举条目 
        entry=(ZipEntry) enu.nextElement(); //得到压缩条目 
        vec.add(entry.getName());  //增加文件到Vector内    
      } 
      files.setListData(vec); //设置文件列表框数据 
      files.getSelectedValues(); 
    } 
    catch (Exception ex){ 
      ex.printStackTrace(); //输出错误信息 
    }     
  } 
  public void extractFile(String name){ //解压文件 
    try{ 
    ZipEntry entry=zFile.getEntry(name);  
    entry.getComment(); 
    entry.getCompressedSize(); 
    entry.getCrc(); 
    entry.isDirectory(); 
    entry.getSize(); 
    entry.getMethod(); 
    InputStream in=zFile.getInputStream(entry); //得到文件输入流 
    File file=new File(name); //实例化文件对象 
    FileOutputStream out=new FileOutputStream(file); //得到文件输出流 
    byte[] buffer=new byte[1024]; //缓冲区大小 
    int length; 
    while((length = in.read(buffer)) != -1) { //循环读取数据 
      out.write(buffer, 0, length); //写数据到输出流 
    } 
      JOptionPane.showMessageDialog(ZipExtractDemo.this,"解压成功,解压到:"+file.getAbsolutePath());  
    in.close(); //关闭输入流 
    out.close(); //关闭输出流   
    } catch (Exception ex){} 
  } 
  public static void main(String[] args){ 
    new ZipExtractDemo(); 
  } 
}

Summary

The above is the detailed content of Example of how to compress and decompress files in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft