Java examples for java.lang:String Compress
compress String
/*// w w w . j ava2 s . c o m * Copyright 2007, 2012 Stephen Fisher and Junhyong Kim, University of * Pennsylvania. * * This file is part of Glo-DB. * * Glo-DB is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Glo-DB is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Glo-DB. If not, see <http://www.gnu.org/licenses/>. * * @(#)GloDBUtils.java */ //package com.java2s; import java.util.zip.Deflater; import java.io.ByteArrayOutputStream; public class Main { public static byte[] compressString(String val) { byte[] bVal = val.getBytes(); // Create the compressor with highest level of compression Deflater compressor = new Deflater(); compressor.setLevel(Deflater.BEST_SPEED); // Give the compressor the data to compress compressor.setInput(bVal); compressor.finish(); // Create an expandable byte array to hold the compressed data. // You cannot use an array that's the same size as the orginal because // there is no guarantee that the compressed data will be smaller than // the uncompressed data. ByteArrayOutputStream bos = new ByteArrayOutputStream(val.length()); // Compress the data byte[] buf = new byte[2048]; while (!compressor.finished()) { int count = compressor.deflate(buf); bos.write(buf, 0, count); } try { bos.close(); } catch (Exception e) { System.err.println(e); } return bos.toByteArray(); } }