欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java使用 ZipOutputStream 压缩zip文件,,如下示例代码packag

来源: javaer 分享于  点击 11281 次 点评:233

java使用 ZipOutputStream 压缩zip文件,,如下示例代码packag


如下示例代码

package cn.outofmemory.snippets.core;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.ZipOutputStream;public class CreateZipFileFromSingleFileWithZipOutputStream {    public static void main(String[] args) {        String zipFile = "C:/archive.zip";        String srcFilename = "C:/srcfile.txt";        try {            // create byte buffer            byte[] buffer = new byte[1024];            FileOutputStream fos = new FileOutputStream(zipFile);            ZipOutputStream zos = new ZipOutputStream(fos);            File srcFile = new File(srcFilename);            FileInputStream fis = new FileInputStream(srcFile);            // begin writing a new ZIP entry, positions the stream to the start of the entry data            zos.putNextEntry(new ZipEntry(srcFile.getName()));            int length;            while ((length = fis.read(buffer)) > 0) {                zos.write(buffer, 0, length);            }            zos.closeEntry();            // close the InputStream            fis.close();            // close the ZipOutputStream            zos.close();        }        catch (IOException ioe) {            System.out.println("Error creating zip file" + ioe);        }    }}
相关栏目:

用户点评