搜尋
首頁Javajava教程java對檔案的壓縮與解壓縮

java對檔案的壓縮與解壓縮

Jul 17, 2017 pm 02:25 PM
java壓縮解壓縮

一 概述

1.目录进入点

目录进入点是文件在压缩文件中的映射,代表压缩文件。压缩文件时,创建目录进入点,将文件写入该目录进入点。解压时,获取目录进入点,将该目录进入点的内容写入硬盘指定文件。

如果目录进入点是一个文件夹,在命名时必须以路径分隔符结尾,在Window操作系统中名称分隔符为“/”。

2.文件的自动创建

无论是调用createNewFile()创建文件,还是在创建输出流时由输出流负责创建文件,都必须保证父路径已经存在,否则文件无法创建。

3.目录的创建

  • mkdirs():创建多级目录。

  • mkdir():创建一级目录,如果父路径不存在,创建失败。

二 压缩

1.创建目录进入点

首先为文件或者文件夹创建目录进入点,目录进入点的名称为当前文件相对于压缩文件的路径,文件夹的目录进入点名称必须以名称分隔符结尾,以区别于文件。

ZipEntry entry = new ZipEntry(压缩文件夹名称 + File.separator+文件或文件夹路径);

2.写入目录进入点

使用ZipOutputStream输出流将文件写入对应目录进入点中,写入完成,关闭目录进入点。

3.Demo

package com.javase.io;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;import java.util.zip.ZipOutputStream;public class ZipUtils {/** * 压缩一个文件夹
     * 
     * @throws IOException     */public void zipDirectory(String path) throws IOException {
        File file = new File(path);
        String parent = file.getParent();
        File zipFile = new File(parent, file.getName() + ".zip");
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
        zip(zos, file, file.getName());
        zos.flush();
        zos.close();
    }/** * 
     * @param zos
     *            压缩输出流
     * @param file
     *            当前需要压缩的文件
     * @param path
     *            当前文件相对于压缩文件夹的路径
     * @throws IOException     */private void zip(ZipOutputStream zos, File file, String path) throws IOException {// 首先判断是文件,还是文件夹,文件直接写入目录进入点,文件夹则遍历if (file.isDirectory()) {
            ZipEntry entry = new ZipEntry(path + File.separator);// 文件夹的目录进入点必须以名称分隔符结尾            zos.putNextEntry(entry);
            File[] files = file.listFiles();for (File x : files) {
                zip(zos, x, path + File.separator + x.getName());
            }
        } else {
            FileInputStream fis = new FileInputStream(file);// 目录进入点的名字是文件在压缩文件中的路径ZipEntry entry = new ZipEntry(path);
            zos.putNextEntry(entry);// 建立一个目录进入点int len = 0;byte[] buf = new byte[1024];while ((len = fis.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            zos.flush();
            fis.close();
            zos.closeEntry();// 关闭当前目录进入点,将输入流移动下一个目录进入点        }
    }}

三 解压文件

1.基本思路

解压文件时,先获取压缩文件中的目录进入点,根据该目录进入点创建文件对象,将目录进入点的内容写入硬盘文件中。

2.Demo

package com.javase.io;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;import java.util.zip.ZipOutputStream;public class ZipUtils {private String basePath;/** * 解压文件
     * 
     * @param unzip
     * @throws IOException     */public void unzip(String unzip) throws IOException {
        File file = new File(unzip);
        basePath = file.getParent();
        FileInputStream fis = new FileInputStream(file);
        ZipInputStream zis = new ZipInputStream(fis);
        unzip(zis);
    }private void unzip(ZipInputStream zis) throws IOException {
        ZipEntry entry = zis.getNextEntry();if (entry != null) {
            File file = new File(basePath + File.separator + entry.getName());if (file.isDirectory()) {// 可能存在空文件夹if (!file.exists())
                    file.mkdirs();
                unzip(zis);
            } else {
                File parentFile = file.getParentFile();if (parentFile != null && !parentFile.exists())
                    parentFile.mkdirs();
                FileOutputStream fos = new FileOutputStream(file);// 输出流创建文件时必须保证父路径存在int len = 0;byte[] buf = new byte[1024];while ((len = zis.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.flush();
                fos.close();
                zis.closeEntry();
                unzip(zis);
            }
        }
    }

}

 

程序实现了ZIP压缩。共分为2部分 : 压缩(compression)与解压(decompression)

大致功能包括用了多态,递归等Java核心技术,可以对单个文件和任意级联文件夹进行压缩和解压。 需在代码中自定义源输入路径和目标输出路径。 

package com.han;    
import java.io.*;  
import java.util.zip.*;  
  
/** 
 * 程序实现了ZIP压缩。共分为2部分 : 压缩(compression)与解压(decompression) 
 * <p> 
 * 大致功能包括用了多态,递归等JAVA核心技术,可以对单个文件和任意级联文件夹进行压缩和解压。 需在代码中自定义源输入路径和目标输出路径。 
 * <p> 
 * 在本段代码中,实现的是压缩部分;解压部分见本包中Decompression部分。 
 *  
 * @author HAN 
 *  
 */  
  
public class MyZipCompressing {  
    private int k = 1; // 定义递归次数变量  
  
    public MyZipCompressing() {  
        // TODO Auto-generated constructor stub  
    }  
  
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        MyZipCompressing book = new MyZipCompressing();  
        try {  
            book.zip("C:\\Users\\Gaowen\\Desktop\\ZipTestCompressing.zip",  
                    new File("C:\\Users\\Gaowen\\Documents\\Tencent Files"));  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
  
    }  
  
    private void zip(String zipFileName, File inputFile) throws Exception {  
        System.out.println("压缩中...");  
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(  
                zipFileName));  
        BufferedOutputStream bo = new BufferedOutputStream(out);  
        zip(out, inputFile, inputFile.getName(), bo);  
        bo.close();  
        out.close(); // 输出流关闭  
        System.out.println("压缩完成");  
    }  
  
    private void zip(ZipOutputStream out, File f, String base,  
            BufferedOutputStream bo) throws Exception { // 方法重载  
        if (f.isDirectory()) {  
            File[] fl = f.listFiles();  
            if (fl.length == 0) {  
                out.putNextEntry(new ZipEntry(base + "/")); // 创建zip压缩进入点base  
                System.out.println(base + "/");  
            }  
            for (int i = 0; i < fl.length; i++) {  
                zip(out, fl[i], base + "/" + fl[i].getName(), bo); // 递归遍历子文件夹  
            }  
            System.out.println("第" + k + "次递归");  
            k++;  
        } else {  
            out.putNextEntry(new ZipEntry(base)); // 创建zip压缩进入点base  
            System.out.println(base);  
            FileInputStream in = new FileInputStream(f);  
            BufferedInputStream bi = new BufferedInputStream(in);  
            int b;  
            while ((b = bi.read()) != -1) {  
                bo.write(b); // 将字节流写入当前zip目录  
            }  
            bi.close();  
            in.close(); // 输入流关闭  
        }  
    }  
}


 


package com.han;  
  
import java.io.*;  
import java.util.zip.*;  
/** 
 * 程序实现了ZIP压缩。共分为2部分 : 
 * 压缩(compression)与解压(decompression) 
 * <p> 
 * 大致功能包括用了多态,递归等JAVA核心技术,可以对单个文件和任意级联文件夹进行压缩和解压。 
 * 需在代码中自定义源输入路径和目标输出路径。 
 * <p> 
 * 在本段代码中,实现的是解压部分;压缩部分见本包中compression部分。 
 * @author HAN 
 * 
 */  
public class CopyOfMyzipDecompressing {  
      
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        long startTime=System.currentTimeMillis();  
        try {  
            ZipInputStream Zin=new ZipInputStream(new FileInputStream(  
                    "C:\\Users\\HAN\\Desktop\\stock\\SpectreCompressed.zip"));//输入源zip路径  
            BufferedInputStream Bin=new BufferedInputStream(Zin);  
            String Parent="C:\\Users\\HAN\\Desktop"; //输出路径(文件夹目录)  
            File Fout=null;  
            ZipEntry entry;  
            try {  
                while((entry = Zin.getNextEntry())!=null && !entry.isDirectory()){  
                    Fout=new File(Parent,entry.getName());  
                    if(!Fout.exists()){  
                        (new File(Fout.getParent())).mkdirs();  
                    }  
                    FileOutputStream out=new FileOutputStream(Fout);  
                    BufferedOutputStream Bout=new BufferedOutputStream(out);  
                    int b;  
                    while((b=Bin.read())!=-1){  
                        Bout.write(b);  
                    }  
                    Bout.close();  
                    out.close();  
                    System.out.println(Fout+"解压成功");      
                }  
                Bin.close();  
                Zin.close();  
            } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        } catch (FileNotFoundException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        long endTime=System.currentTimeMillis();  
        System.out.println("耗费时间: "+(endTime-startTime)+" ms");  
    }  
  
}


以上是java對檔案的壓縮與解壓縮的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Java平台是否獨立,如果如何?Java平台是否獨立,如果如何?May 09, 2025 am 12:11 AM

Java是平台獨立的,因為其"一次編寫,到處運行"的設計理念,依賴於Java虛擬機(JVM)和字節碼。 1)Java代碼編譯成字節碼,由JVM解釋或即時編譯在本地運行。 2)需要注意庫依賴、性能差異和環境配置。 3)使用標準庫、跨平台測試和版本管理是確保平台獨立性的最佳實踐。

關於Java平台獨立性的真相:真的那麼簡單嗎?關於Java平台獨立性的真相:真的那麼簡單嗎?May 09, 2025 am 12:10 AM

Java'splatFormIndenceIsnotsimple; itinvolvesComplexities.1)jvmcompatiblemustbebeeniblemustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)

Java平台獨立性:Web應用程序的優勢Java平台獨立性:Web應用程序的優勢May 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM解釋:Java虛擬機的綜合指南JVM解釋:Java虛擬機的綜合指南May 09, 2025 am 12:04 AM

thejvmistheruntimeenvorment forexecutingjavabytecode,Cocucialforjava的“ WriteOnce,RunanyWhere”能力

Java的主要功能:為什麼它仍然是頂級編程語言Java的主要功能:為什麼它仍然是頂級編程語言May 09, 2025 am 12:04 AM

JavaremainsatopchoicefordevelopersduetoitsplatFormentence,對象與方向設計,強度,自動化的MememoryManagement和ComprechensivestAndArdArdArdLibrary

Java平台獨立性:這對開發人員意味著什麼?Java平台獨立性:這對開發人員意味著什麼?May 08, 2025 am 12:27 AM

Java'splatFormIndependecemeansDeveloperScanWriteCeandeCeandOnanyDeviceWithouTrecompOlding.thisAcachivedThroughThroughTheroughThejavavirtualmachine(JVM),WhaterslatesbyTecodeDecodeOdeIntComenthendions,允許univerniverSaliversalComplatibilityAcrossplatss.allospplats.s.howevss.howev

如何為第一次使用設置JVM?如何為第一次使用設置JVM?May 08, 2025 am 12:21 AM

要設置JVM,需按以下步驟進行:1)下載並安裝JDK,2)設置環境變量,3)驗證安裝,4)設置IDE,5)測試運行程序。設置JVM不僅僅是讓其工作,還包括優化內存分配、垃圾收集、性能調優和錯誤處理,以確保最佳運行效果。

如何查看產品的Java平台獨立性?如何查看產品的Java平台獨立性?May 08, 2025 am 12:12 AM

toensurejavaplatFormIntence,lofterTheSeSteps:1)compileAndRunyOpplicationOnmultPlatFormSusiseDifferenToSandjvmversions.2)upureizeci/cdppipipelinelikeinkinslikejenkinsorgithikejenkinsorgithikejenkinsorgithikejenkinsorgithike forautomatecross-plateftestesteftestesting.3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境