Java通過zip壓縮文件

pkiek23 9年前發布 | 747 次閱讀 Java

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);
    }

}

} </pre>

 本文由用戶 pkiek23 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!