Java IO压缩流-压缩输出、压缩输入

压缩流主要实现文件的压缩:

1.ZipEntry:
public class ZipEntry extends Object implements Cloneable; // 表达压缩实体
public ZipEntry(String name);// 为压缩实体指定含路径信息的名子
    Creates a new zip entry with the specified name.
public ZipEntry(ZipEntry e);//
    Creates a new zip entry with fields taken from the specified zip entry.  
public String getName()
    Returns the name of the entry.      
public void setComment(String comment)
    Sets the optional comment string for the entry.
public String getComment()
    Returns the comment string for the entry, or null if none.
public boolean isDirectory()
    Returns true if this is a directory entry. A directory entry is defined to be one whose name ends with a ‘/’.
2.ZipFile:
public class ZipFile extends Object;
This class is used to read entries from a zip file.                
public ZipFile(File file)
        throws ZipException,
               IOException
    Opens a ZIP file for reading given the specified File object.
public ZipFile(File file,
               int mode)
        throws IOException
    Opens a new ZipFile to read from the specified File object in the specified mode. The mode argument must be either OPEN_READ or OPEN_READ | OPEN_DELETE.
public ZipFile(String name)
        throws IOException
    Opens a zip file for reading.
public ZipEntry getEntry(String name)
    Returns the zip file entry for the specified name, or null if not foun
public InputStream getInputStream(ZipEntry entry)
                           throws IOException
    Returns an input stream for reading the contents of the specified zip file entry.
    Closing this ZIP file will, in turn, close all input streams that have been returned by invocations of this method.
public String getName()
    Returns the path name of the ZIP file.
public void close()
           throws IOException
    Closes the ZIP file.
3.ZipInputStream:
public class ZipInputStream extends InflaterInputStream;
This class implements an input stream filter for reading files in the ZIP file format. Includes support for both compressed and uncompressed entries.
public ZipInputStream(InputStream in)
    Creates a new ZIP input stream.
public ZipEntry getNextEntry()
                      throws IOException
    Reads the next ZIP file entry and positions the stream at the beginning of the entry data.
public void closeEntry()
                throws IOException
    Closes the current ZIP entry and positions the stream for reading the next entry.
public void close()
           throws IOException
    Closes this input stream and releases any system resources associated with the stream.
4.ZipOutputStream:
public class ZipOutputStream extends DeflaterOutputStream;
This class implements an output stream filter for writing files in the ZIP file format. Includes support for both compressed and uncompressed entries.
public ZipOutputStream(OutputStream out)
    Creates a new ZIP output stream.
public void setComment(String comment)
    Sets the ZIP file comment.
public void putNextEntry(ZipEntry e)
                  throws IOException
public void closeEntry()
                throws IOException
    Closes the current ZIP entry and positions the stream for writing the next entry.
public void write(byte[] b,
                  int off,
                  int len)
           throws IOException
public void write(int b)
           throws IOException
    Writes a byte to the compressed output stream. This method will block until the byte can be written.           
public void close()
           throws IOException
——-压缩单个磁盘文件:
package com.mldn;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;
public class ZipDemo
{
        public static void main(String[] args)
        {
                String path = File.separator + “home” + File.separator + “administrator” + File.separator;        // 操作目录
                File sourceFile = new File(path + “111”);        // 实例化文件
                File zipFile = new File(path + “111.zip”);        // 实例化文件
                InputStream input = null;                                // 声明字节输入流
                try
                {
                        input = new FileInputStream(sourceFile);        // 实例化字节输入流
                }
                catch (FileNotFoundException e)
                {
                        System.out.println(“源文件不存在!”);
                }
                OutputStream output = null;                                // 声明字节输出流
                try
                {
                        output = new FileOutputStream(zipFile);        // 实例化字节输出流
                }
                catch (FileNotFoundException e)
                {
                        System.out.println(“操作文件不存在!”);
                }               
                ZipOutputStream zipOut = null;                                // 声明压缩输出流
                zipOut = new ZipOutputStream(output);                 // 实例化压缩流
                String entryName = sourceFile.getName();
                ZipEntry entry = new ZipEntry(entryName);        // 实例化zip实体
                try
                {
                        zipOut.putNextEntry(entry);                                        // 指定压缩实体对象,定位当前实体数据,关闭其他实体,调用默认压缩方法准备写数据
                }
                catch (IOException e)
                {
                        e.printStackTrace();
                }
                zipOut.setComment(“文本文档!”);                                // 设置注释
                int temp = 0;
                try
                {
                        while ((temp = input.read()) != -1)
                        {
                                zipOut.write(temp);                                                // 压缩数据
                        }
                }
                catch (IOException e)
                {
                        e.printStackTrace();
                }
                try
                {
                        zipOut.close();                // 关闭压缩流
                        input.close();                // 关闭输入流
                }
                catch (IOException e)
                {
                        e.printStackTrace();
                }
                System.out.println(“文件压缩完毕!”);
        }
}
/*
administrator@xu-desktop:~$ javac -d . work/ZipDemo.java
administrator@xu-desktop:~$ java com.mldn.ZipDemo
文件压缩完毕!
*/

————实现压缩类:可以将文件压缩为.zip格式;
/*
        @version 2010-03-28
        @author k187.com
        ~“`该类可以把文件或文件夹压缩为.zip格式,其他格式的实现类似!
*/
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;
import java.util.Scanner;
public class Zip
{
        public static void main(String[] args) throws Exception
        {
                new Zip();                        // 系统开始!
        }
        private File file = null;                                 // 源文件
        private File zipFile = null;                         // 压缩文件
        private InputStream input = null;                 // 声明字节输入流
        private OutputStream out = null;                 // 声明字节输出流
        private ZipOutputStream zipOut = null;         // 声明压缩输出流
        public Zip()
        {
                // 系统初始化:源文件路径;压缩文件路径;
                System.out.println(“请输入源文件完整路径名:”);               
                String sourceFilePath = this.getPath();
                System.out.println(“请输入压缩文件完整路径名:”);
                String zipFilePath = this.getPath();
                this.initZip(sourceFilePath, zipFilePath);
                // 若是文件夹:压缩文件夹;单个文件:压缩单个文件;
                if (this.getFile().isDirectory())
                {
                        this.zipFolders(this.getFile(), this.getFile().getName());       
                }
                else
                {
                        this.zipFile(this.getFile());
                }
                // 压缩完成:系统关闭退出;
                this.close();
        }
        public String getPath()
        {               
                Scanner sc = null;                                // 声明扫描器
                sc = new Scanner(System.in).useDelimiter(“\n”);        // 从标准输入读取,按回车提交
                StringBuffer buf = new StringBuffer();                        // 接收数据
                buf.append(sc.nextLine());                // 读取
                return buf.toString();                        // 返回用户输入
        }
        public File getFile()                                // 获取源文件
        {
                return this.file;
        }
        public void initZip(String fileName, String zipFileName)
        {
                this.file = new File(fileName);                         // 实例化源文件
                this.zipFile = new File(zipFileName);                 // 实例化压缩文件
                try
                {
                        this.out = new FileOutputStream(zipFile);// 实例化字节输出流
                }
                catch (FileNotFoundException e)
                {
                        System.out.println(“压缩文件输出路径不对或者没有访问权限!”);
                        e.printStackTrace();
                }
                this.zipOut = new ZipOutputStream(out);         // 实例化压缩流
        }       
        public void zipFolders(File file, String folderName)                                // 压缩含有子文件夹的整个文件夹
        {       
                if (file.isDirectory())                                                                                 // 当前文件是目录,1.设置目录实体,2.处理目录下内容
                {
                        if (folderName.equals(file.getName()))                                                // 这是压缩文件夹的根目录
                        {                       
                                folderName += “/”;                                                                                // 修改当前实体路径:用于标记当前访问的文件位置
                                this.putNextEntry(folderName);                                                        // 为目录设置ZipEntry:目录的实体名:文件名+“/”               
                        }
                        else                                                                                                                // 这是压缩文件夹的子文件夹
                        {       
                                folderName += file.getName() + “/”;                                                // 此处String对象的使用可能会产生大量内存垃圾
                                this.putNextEntry(folderName);                                       
                        }
                        File[] lists = file.listFiles();                                                         // 列出当前目录下的所有文件对象(目录也是文件)
                        if (lists != null)                                                                                        // 当前目录下有内容,对内容逐一处理
                        {
                                for (File f : lists)
                                {                                                               
                                        zipFolders(f, folderName);                                                     // 回调
                                }
                        }                       
                }
                else                                                                  // 不是目录,是单个文件,直接写入压缩流
                {                       
                        this.zipFolder(file, folderName); // 压缩当前文件file,
                }
        }
        public void zipFolder(File file, String folderName)                                // 压缩文件夹,不含子文件夹的
        {       
                this.putNextEntry(folderName + file.getName());
                this.doZip(file);
        }
        public void zipFile(File file)                 // 压缩单个文件
        {               
                this.putNextEntry(file.getName());// 放置实体
                this.doZip(file);
        }
        public void putNextEntry(String currentEntry)                // 放置当前压缩文件实体对象
        {
                ZipEntry entry = new ZipEntry(currentEntry);        // 实例化zip实体
                try
                {
                        zipOut.putNextEntry(entry);
                }
                catch (IOException e)
                {
                        System.out.println(“Error Begins writing a new ZIP file entry and ” +
                                                                “positions the stream to the start of the entry data. “);
                        e.printStackTrace();
                }
        }
        private void doZip(File file)                        // 执行压缩读写操作
        {
                int temp = 0;
                try
                {
                        this.input = new FileInputStream(file); // 实例化当前文件输入流对象
                }
                catch (FileNotFoundException e)
                {
                        System.out.println(“未找到您要压缩的文件:” + file.getName() + “\n请确认这是要压缩的文件,并且是存在的!”);
                        e.printStackTrace();
                }
                try
                {
                        while ((temp = this.input.read()) != -1)
                        {
                                zipOut.write(temp); // 压缩数据
                        }
                        this.input.close();         // 关闭当前输入流
                }
                catch (IOException e)
                {
                        System.out.println(“文件读或写时错误,请确认当前您有操作权限,\n请确认压缩文件保存路径是正确的!”);
                        e.printStackTrace();
                }
        }
        public void close()                                        // 关闭流
        {
                try
                {
                        this.zipOut.close();                 // 关闭压缩流
                        this.out.close();                        // 关闭字节输出流
                } catch (IOException e)
                {
                        System.out.println(“系统退出异常,请查看” + this.zipFile.getName());
                        e.printStackTrace();
                }               
                System.out.println(“文件压缩完毕!文件目录:” + this.zipFile.getPath());
        }
}
/*
administrator@xu-desktop:~/work$ java Zip
请输入源文件完整路径名:
/home/administrator/file
请输入压缩文件完整路径名:
/home/administrator/file.zip
压缩file/文件.
压缩file/s/文件.
压缩file/s/abcd.txt文件.
压缩file/s/sdfsdf/文件.
压缩file/s/sdfsdf/sdfdsfsdf文件.
压缩file/s/sdfsdf/sdfsdfsdfsdfsd文件.
压缩file/s/sdf.txt文件.
压缩file/dest.txt文件.
压缩file/system.out.txt文件.
压缩file/ps.txt文件.
压缩file/myFile.txt文件.
压缩file/file.txt文件.
压缩file/Message_zh_CN.properties文件.
压缩file/Message.2.properties文件.
压缩file/bbnb/文件.
压缩file/mm  sldfjl/文件.
压缩file/mm  sldfjl/sdfsd文件.
压缩file/Message_en_US.properties文件.
文件压缩完毕!文件目录:/home/administrator/file.zip
*/

————实现多目录文件夹解压zip格式:
package com.mldn;
import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipEntry;
import java.util.Scanner;
public class Unzip
{
        public static void main(String[] args)throws Exception
        {
                new Unzip();
        }
        private File file = null;        // 压缩包文件
        private File outFile = null;// 解压缩文件
        private ZipFile zipFile = null;        // 压缩包读取文件:打开压缩包文件
        private ZipInputStream zipInput = null;        // 压缩文件输入流:读取ZipFile的压缩实体
        private InputStream input = null;                // 字节输入流:读取磁盘文件到流
        private OutputStream out = null;                // 字节输出流:写出内存数据到流
        private ZipEntry entry = null;                        // 压缩实体
        public  Unzip() throws Exception
        {
                // 系统初始化:压缩包文件路径;
                System.out.println(“输入压缩包完整路径名:”);               
                String sourcePath = this.getPath();       
                System.out.println(“输入解压到路径:”);
                String unzipPath = this.getPath();                       
                this.initUnzip(sourcePath);
                // 解压缩;
                this.unzip(unzipPath);
                // 系统关闭退出;
        }
        public String getPath()
        {               
                Scanner sc = null;                                // 声明扫描器
                sc = new Scanner(System.in).useDelimiter(“\n”);        // 从标准输入读取,按回车提交
                StringBuffer buf = new StringBuffer();                        // 接收数据
                buf.append(sc.nextLine());                // 读取
                return buf.toString();                        // 返回用户输入
        }
        public File getFile()                                // 获取压缩包文件
        {
                return this.file;
        }
        public InputStream getInputStream()                        // 获取压缩包读取流
        {
                return this.input;
        }
        public void initUnzip(String sourcePath) throws Exception
        {
                this.file = new File(sourcePath);        // 实例化压缩包文件
                this.zipFile = new ZipFile(this.getFile());        // 实例化压缩读取文件
                //this.input = new FileInputStream(this.getFile());// 实例化压缩包文件字节输入流
                this.zipInput = new ZipInputStream(new FileInputStream(this.getFile()));// 压缩输入流,读取压缩实体
        }
        public void unzip(String unzipPath) throws Exception
        {               
                while ((this.entry = this.zipInput.getNextEntry()) != null)
                {
                        System.out.println(“解压缩” + entry.getName() + “文件.”);
                        this.outFile = new File(unzipPath + File.separator + this.entry.getName());
                        System.out.println(unzipPath + File.separator + this.entry.getName());                       
                        if (entry.isDirectory())// if cureent entry is directory,make it!
                        {
                                outFile.mkdirs();        // mkdirs will make all of directory with upon current directory nonexists
                        }
                        else                                        // FileOutputStream could’nt write a directory but a file in Linux
                        {                       
                                if (!this.outFile.getParentFile().exists())
                                {                                       
                                        this.outFile.mkdirs();        // if current entry is a file , and all of parent directory is nonexists
                                }
                                this.input = this.zipFile.getInputStream(this.entry);
                                this.out = new FileOutputStream(this.outFile);
                                int temp = 0;
                                while ((temp = this.input.read()) != -1)
                                {
                                        this.out.write(temp);
                                }
                                this.input.close();
                                this.out.close();
                        }
                        this.zipInput.closeEntry();
                }
                this.zipInput.close();
        }
}
/*
root@xu-desktop:/home/administrator# java com.mldn.Unzip
输入压缩包完整路径名:
/home/administrator/file.zip
输入解压到路径:
/home/administrator/file1
解压缩file/文件.
/home/administrator/file1/file/
解压缩file/s/文件.
/home/administrator/file1/file/s/
解压缩file/s/abcd.txt文件.
/home/administrator/file1/file/s/abcd.txt
解压缩file/s/sdfsdf/文件.
/home/administrator/file1/file/s/sdfsdf/
解压缩file/s/sdfsdf/sdfdsfsdf文件.
/home/administrator/file1/file/s/sdfsdf/sdfdsfsdf
解压缩file/s/sdfsdf/sdfsdfsdfsdfsd文件.
/home/administrator/file1/file/s/sdfsdf/sdfsdfsdfsdfsd
解压缩file/s/sdf.txt文件.
/home/administrator/file1/file/s/sdf.txt
解压缩file/dest.txt文件.
/home/administrator/file1/file/dest.txt
解压缩file/system.out.txt文件.
/home/administrator/file1/file/system.out.txt
解压缩file/ps.txt文件.
/home/administrator/file1/file/ps.txt
解压缩file/myFile.txt文件.
/home/administrator/file1/file/myFile.txt
解压缩file/file.txt文件.
/home/administrator/file1/file/file.txt
解压缩file/Message_zh_CN.properties文件.
/home/administrator/file1/file/Message_zh_CN.properties
解压缩file/Message.2.properties文件.
/home/administrator/file1/file/Message.2.properties
解压缩file/bbnb/文件.
/home/administrator/file1/file/bbnb/
解压缩file/mm  sldfjl/文件.
/home/administrator/file1/file/mm  sldfjl/
解压缩file/mm  sldfjl/sdfsd文件.
/home/administrator/file1/file/mm  sldfjl/sdfsd
解压缩file/Message_en_US.properties文件.
/home/administrator/file1/file/Message_en_US.properties
*/

声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 嗅谱网
转载请注明:转自《Java IO压缩流-压缩输出、压缩输入
本文地址:http://www.xiupu.net/archives-102.html
关注公众号:嗅谱网

赞赏

wechat pay微信赞赏alipay pay支付宝赞赏

上一篇
下一篇

相关文章

在线留言

你必须 登录后 才能留言!