
package com.dxhy.core.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;

public class GzipStringUtil {
    public GzipStringUtil() {}

    public static String compress(String str) throws IOException {
        if (str != null && str.length() != 0) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes());
            gzip.close();
            return out.toString("ISO-8859-1");
        } else {
            return str;
        }
    }

    public static String uncompress(String str) throws IOException {
        if (str != null && str.length() != 0) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
            GZIPInputStream gunzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];

            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }

            return out.toString();
        } else {
            return str;
        }
    }

    public static String readToString(String fileName) throws IOException {
        String encoding = "UTF-8";
        File file = new File(fileName);
        StringBuffer build = new StringBuffer();
        LineIterator it = FileUtils.lineIterator(file, encoding);

        try {
            while (it.hasNext()) {
                String line = it.nextLine();
                build.append(line);
            }
        } finally {
            LineIterator.closeQuietly(it);
        }

        return build.toString();
    }
}
