compress To Bytes - Java File Path IO

Java examples for File Path IO:Zip File

Description

compress To Bytes

Demo Code


//package com.java2s;
import java.io.*;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Main {
    public static byte[] compressToBytes(String str) {
        if (str == null) {
            return null;
        }/*from w  ww . jav  a2 s  .co  m*/

        byte[] zipBytes = null;
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ZipOutputStream zipOut = null;

        try {
            zipOut = new ZipOutputStream(byteOut);
            zipOut.putNextEntry(new ZipEntry("zipEntry"));
            zipOut.write(str.getBytes());
            zipOut.closeEntry();
            zipBytes = byteOut.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipOut != null) {
                try {
                    zipOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return zipBytes;
    }
}

Related Tutorials