byte Tôi có một vấn đề trong mã:GZIP chuỗi giải nén và chuyển đổi
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);
}
này java.io.IOException đang ném: định dạng lạ (kỳ diệu số ef1f)
GZIPInputStream gs = new GZIPInputStream(bais);
Nó chỉ ra rằng khi chuyển đổi byte new String (b1)
và byte b [] = str.getBytes()
byte là "hư hỏng". Tại đầu ra của dòng, chúng ta đã có nhiều byte hơn. Nếu bạn tránh chuyển đổi thành chuỗi và làm việc trên dòng có byte - mọi thứ đều hoạt động. Xin lỗi vì tiếng Anh của tôi.
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);
}
Tôi sử dụng chức năng này để giải nén máy chủ phản ứng. Cảm ơn vì sự giúp đỡ.
Tôi sử dụng default_charset() == "UTF-8". Đây chỉ là thử nghiệm. –
@AlexandrErofeev: Sẽ không rõ khi ai đọc * Mã * Mã hóa bạn đang sử dụng. IMO nó tốt hơn nhiều để nói rõ ràng. (Và nếu nó chỉ là một thử nghiệm, loại bỏ tất cả các xử lý ngoại lệ hoàn toàn, và chỉ để cho tất cả các phương thức ném 'IOException' - nó sẽ đơn giản hóa mã.) –