Mam problem w postaci kodu:GZIP dekompresji ciąg bajtów i konwersja
private static String compress(String str)
{
String str1 = null;
ByteArrayOutputStream bos = null;
try
{
bos = new ByteArrayOutputStream();
BufferedOutputStream dest = null;
byte b[] = str.getBytes();
GZIPOutputStream gz = new GZIPOutputStream(bos,b.length);
gz.write(b,0,b.length);
bos.close();
gz.close();
}
catch(Exception e) {
System.out.println(e);
e.printStackTrace();
}
byte b1[] = bos.toByteArray();
return new String(b1);
}
private static String deCompress(String str)
{
String s1 = null;
try
{
byte b[] = str.getBytes();
InputStream bais = new ByteArrayInputStream(b);
GZIPInputStream gs = new GZIPInputStream(bais);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int numBytesRead = 0;
byte [] tempBytes = new byte[6000];
try
{
while ((numBytesRead = gs.read(tempBytes, 0, tempBytes.length)) != -1)
{
baos.write(tempBytes, 0, numBytesRead);
}
s1 = new String(baos.toByteArray());
s1= baos.toString();
}
catch(ZipException e)
{
e.printStackTrace();
}
}
catch(Exception e) {
e.printStackTrace();
}
return s1;
}
public String test() throws Exception
{
String str = "teststring";
String cmpr = compress(str);
String dcmpr = deCompress(cmpr);
}
ten kod throw java.io.IOException: nieznany format (magiczna liczba ef1f)
GZIPInputStream gs = new GZIPInputStream(bais);
Okazuje się, że podczas konwersji bajtów new String (b1)
i byte b [] = str.getBytes()
bajtów są "zepsute". Na wyjściu linii mamy już więcej bajtów. Jeśli unikniesz konwersji na ciąg i pracujesz na linii z bajtami - wszystko działa. Przepraszam za mój angielski.
public String unZip(String zipped) throws DataFormatException, IOException {
byte[] bytes = zipped.getBytes("WINDOWS-1251");
Inflater decompressed = new Inflater();
decompressed.setInput(bytes);
byte[] result = new byte[100];
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
while (decompressed.inflate(result) != 0)
buffer.write(result);
decompressed.end();
return new String(buffer.toByteArray(), charset);
}
Jestem Funkcja ta służy do dekompresji serwera responce. Dzięki za pomoc.
Używam default_charset() == "UTF-8". To tylko test. –
@AlexandrErofeev: Nie będzie jasne, czy ktokolwiek * czyta * Kod, który kodujesz, którego używasz. IMO znacznie lepiej jest podać to wprost. (A jeśli jest to tylko test, całkowicie usuń wszystkie wyjątki i po prostu pozwól wszystkim metodom rzucić 'IOException' - to uprości kod.) –