可能重复:
短文本字符串的最佳压缩算法
我在压缩和解压缩字符串方面需要帮助。
当我尝试压缩较小的字符串时,它会转换为比原始大小更多的字节。但是当我添加更大的字符串时,它会以更少的字节压缩。
我在下面给出我的代码:
package string_compress;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
//@author Administrator
public class Main
{
public static String compress(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}
System.out.println("String length : " + str.length());
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();
String outStr = out.toString("ISO-8859-1");//ISO-8859-1
System.out.println("Output String lenght : " + outStr.length());
return outStr;
}
public static String decompress(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}
System.out.println("Input String length : " + str.length());
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(str.getBytes("ISO-8859-1")));
BufferedReader bf = new BufferedReader(new InputStreamReader(gis, "ISO-8859-1"));
String outStr = "";
String line;
while ((line=bf.readLine())!=null) {
outStr += line;
}
System.out.println("Output String lenght : " + outStr.length());
return outStr;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)throws IOException {
//String filePath = ".\response.txt";
// String string = getFileData(filePath);
String string= "rishi jain is tring to compress the string";
System.out.println("after compress:");
String compressed = Main.compress(string);
System.out.println(compressed);
System.out.println("after decompress:");
String decomp = decompress(compressed);
System.out.println(decomp);
}
}