検索
ホームページJava&#&チュートリアル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 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Javaはまだ新機能に基づいた良い言語ですか?Javaはまだ新機能に基づいた良い言語ですか?May 12, 2025 am 12:12 AM

JavaremainsagoodlanguagedueToitscontinuousevolution androbustecosystem.1)lambdaexpressionsenhancecodereadability andenableFunctionalprogramming.2)streamsalowsolowsolfisitydataprocessing、特に特にlagedatasets.3)硬化系系統系系統系系統系系統

何がJavaを素晴らしいものにしますか?主な機能と利点何がJavaを素晴らしいものにしますか?主な機能と利点May 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence、robustoopsupport、extensiveLibraries、andstrongCommunity.1)PlatformentepenteviajvMallowsCodeTorunonVariousPlatforms.2)oopeatureSlikeEncapsulation、遺伝、およびポリモ系系統型皮下皮質皮下Rich

トップ5のJava機能:例と説明トップ5のJava機能:例と説明May 12, 2025 am 12:09 AM

Javaの5つの主要な特徴は、多型、Lambda Expressions、StreamSapi、ジェネリック、例外処理です。 1。多型により、さまざまなクラスのオブジェクトを一般的なベースクラスのオブジェクトとして使用できます。 2。Lambda式は、コードをより簡潔にし、特にコレクションやストリームの処理に適しています。 3.ストリームサピは、大規模なデータセットを効率的に処理し、宣言操作をサポートします。 4.ジェネリックは、タイプの安全性と再利用性を提供し、型刻印中にタイプエラーがキャッチされます。 5.例外処理は、エラーをエレガントに処理し、信頼できるソフトウェアを作成するのに役立ちます。

Javaのトップ機能は、パフォーマンスとスケーラビリティにどのような影響を与えますか?Javaのトップ機能は、パフォーマンスとスケーラビリティにどのような影響を与えますか?May 12, 2025 am 12:08 AM

java'stoputuressificlynificlytallysperformanceandscalability.1)object-oriented-principleslikepolymorphismenabledscalablecode.2)garbagecolectionAutomateMemorymarymanagemenateButcancausElatenceSuses.3)

JVM Internals:Java Virtual Machineの奥深くに飛び込みますJVM Internals:Java Virtual Machineの奥深くに飛び込みますMay 12, 2025 am 12:07 AM

JVMのコアコンポーネントには、クラスローダー、runtimedataarea、executionEngineが含まれます。 1)クラスローダーは、クラスとインターフェイスの読み込み、リンク、初期化を担当します。 2)runtimedataareaには、Methodarea、Heap、Stack、Pcregister、Nativemethodstackが含まれています。 3)ExecutionEngineは、Bytecodeの実行と最適化を担当する通訳、JitCompiler、GarbageCollectorで構成されています。

Java Virtual Machine(JVM)とは何ですか?初心者のガイドJava Virtual Machine(JVM)とは何ですか?初心者のガイドMay 10, 2025 am 12:10 AM

jvmenablesjavaの「writeonce、runanywhere "bycompilingcodeodoplatform-inndopent bytecode、これはinterpretsorcompilesintintomacine-specificcode.itoptimancewithjitcompilation、管理者向けに管理されています

JVMバージョンは何に影響しますか?JVMバージョンは何に影響しますか?May 10, 2025 am 12:08 AM

JVMバージョンのJavaプログラムに対する影響には、互換性、パフォーマンスの最適化、ガベージコレクションポリシー、セキュリティ、言語機能が含まれます。 1)互換性:コードと依存関係のライブラリが新しいJVMで実行されていることを確認してください。 2)パフォーマンス:新しいJVMは、ゴミコレクションとJITコンピレーションパフォーマンスを改善します。 3)セキュリティ:セキュリティの脆弱性を修正し、全体的なセキュリティを改善します。 4)新機能:Java 8のLambda ExpressionsやJava 17のZGC Garbage Collectorなど、コードの簡素化、効率の向上。

JavaのJVMの理解:プラットフォームの独立性の背後にある秘密JavaのJVMの理解:プラットフォームの独立性の背後にある秘密May 10, 2025 am 12:07 AM

JVMは、Java Bytecodeをマシン固有の命令に変換することにより、Javaの「Write and、Run Everywherewhere」を実装します。 1.クラスローダーはクラスをロードします。 2。ランタイムデータ領域にデータを保存します。 3。エンジンを実行して、bytecodeを変換します。 4.JNIは、他の言語との相互作用を可能にします。 5.ローカルメソッドライブラリはJNIコールをサポートしています。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境