我目前正在尝试使用java.util.zip.*包来执行无损压缩/解压缩。
我已经使用apache 的jar 对用作 Base64 字符集中参数的字符串进行编码和解码。
在我的代码中使用两种静态方法,一种用于压缩,一种用于解压缩。
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.zip.*;
import org.apache.commons.codec.binary.Base64;
public class main {
public String compress(String stringToCompress) throws UnsupportedEncodingException
{
//System.out.println("String to Be Compressed :: " + stringToCompress);
byte[] input = Base64.decodeBase64(stringToCompress);
Deflater compressor = new Deflater();
compressor.setInput(input);
compressor.finish();
byte[] output = new byte[100];
compressor.deflate(output);
return Base64.encodeBase64String(output);
}
public String decompressToString(String stringToDecompress) throws UnsupportedEncodingException, DataFormatException
{
//System.out.println("String to be Decompressed :: " + stringToDecompress);
byte[] input = Base64.decodeBase64(stringToDecompress);
Inflater deCompressor = new Inflater();
deCompressor.setInput(input,0,input.length);
byte[] output = new byte[100];
deCompressor.inflate(output);
deCompressor.end();
return Base64.encodeBase64String(output);
}
public static void main(String[] args) throws UnsupportedEncodingException, DataFormatException {
main m = new main();
String strToBeCompressed = "jhjksdhgfkjdsfhkjhjvblkajnlkdfmvlksjfdovbjaiudhv adjv ajgvoig avigogauguivadfhijbjkla";
String compressedString = m.compress(strToBeCompressed) ;
String deCompressedString = m.decompressToString(compressedString);
System.out.println("Original :: " + strToBeCompressed);
System.out.println("Compressed :: " + compressedString);
System.out.println("decompressed :: " + deCompressedString);
}
}
这是输出。
Original :: jhjksdhgfkjdsfhkjhjvblkajnlkdfmvlksjfdovbjaiudhv adjv ajgvoig avigogauguivadfhijbjkla
Compressed :: eJwBPQDC/44Y5LHYYH5I3bH4ZI4Y725ZGo55ZHX5r5ZLI33aL242ornYb2nY72o4L6IoGr4oKIGroLor2nX4Yo245JXcvx/9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==
decompressed :: jhjksdhgfkjdsfhkjhjvblkajnlkdfmvlksjfdovbjaiudhvadjvajgvoigavigogauguivadfhijbjklQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==
如果您看到输出,则原始字符串和解压缩字符串不匹配。我不知道为什么?谁能告诉我原因。