从C#中的压缩字符串中解压缩java中的字符串

时间:2013-09-04 05:16:17

标签: c# java gzip inflate compression

我正在寻找正确的解决方案来解压缩来自c#code的java中的字符串。我尝试使用java中的许多技术(gzip,inflatter等)。但是没有得到解决方案。我得到了一些解决方案。尝试从c#code中压缩字符串解压缩java中的字符串时出错。

我压缩字符串的C#代码是,

public static string CompressString(string text)
{

   byte[] byteArray = Encoding.GetEncoding(1252).GetBytes(text);//  Encoding.ASCII.GetBytes(text);

   using (var ms = new MemoryStream())
   {
    // Compress the text
    using (var ds = new DeflateStream(ms, CompressionMode.Compress))
    {
     ds.Write(byteArray, 0, byteArray.Length);
    }

    return Convert.ToBase64String(ms.ToArray());
   }
  }

使用

解压缩java中的字符串
private static void compressAndDecompress(){
    try {
        // Encode a String into bytes
        String string = "xxxxxxSAMPLECOMPRESSEDSTRINGxxxxxxxxxx";
        // // Compress the bytes
        byte[] decoded = Base64.decodeBase64(string.getBytes());
        byte[] output = new byte[4096];
        // Decompress the bytes
        Inflater decompresser = new Inflater();
        decompresser.setInput(decoded);

        int resultLength = decompresser.inflate(output);
        decompresser.end();

        // Decode the bytes into a String
        String outputString = new String(output, 0, resultLength, "UTF-8");

        System.out.println(outputString);
    } catch(java.io.UnsupportedEncodingException ex) {    
        ex.printStackTrace();
    } catch (java.util.zip.DataFormatException ex) {
        ex.printStackTrace();
    }
}

运行上面的代码时出现此异常:

java.util.zip.DataFormatException: incorrect header check

请给我java中的示例代码解压缩字符串java.Thanks

3 个答案:

答案 0 :(得分:0)

要压缩的C#代码是

 private string Compress(string text)
    {
        byte[] buffer = Encoding.UTF8.GetBytes(text);
        MemoryStream ms = new MemoryStream();
        using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
        {
            zip.Write(buffer, 0, buffer.Length);
        }

        ms.Position = 0;
        MemoryStream outStream = new MemoryStream();

        byte[] compressed = new byte[ms.Length];
        ms.Read(compressed, 0, compressed.Length);

        byte[] gzBuffer = new byte[compressed.Length + 4];
        System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
        System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
        return Convert.ToBase64String(gzBuffer);
    }

解压缩文本的Java代码是

private String Decompress(String compressedText)
{

    byte[] compressed = compressedText.getBytes("UTF8");
    compressed = org.apache.commons.codec.binary.Base64.decodeBase64(compressed);
    byte[] buffer=new byte[compressed.length-4];
    buffer = copyForDecompression(compressed,buffer, 4, 0);
    final int BUFFER_SIZE = 32;
    ByteArrayInputStream is = new ByteArrayInputStream(buffer);
    GZIPInputStream gis = new GZIPInputStream(is, BUFFER_SIZE);
    StringBuilder string = new StringBuilder();
    byte[] data = new byte[BUFFER_SIZE];
    int bytesRead;
    while ((bytesRead = gis.read(data)) != -1) 
    {
        string.append(new String(data, 0, bytesRead));
    }
    gis.close();
    is.close();
    return string.toString();
}
private  byte[] copyForDecompression(byte[] b1,byte[] b2,int srcoffset,int dstoffset)
{       
    for(int i=0;i<b2.length && i<b1.length;i++)
    {
        b2[i]=b1[i+4];
    }
    return b2;
}

这段代码对我来说非常好。

答案 1 :(得分:0)

有完全相同的问题。可以通过

解决
byte[] compressed = Base64Utils.decodeFromString("mybase64encodedandwithc#zippedcrap");
Inflater decompresser = new Inflater(true);
decompresser.setInput(compressed);
byte[] result = new byte[4096];
decompresser.inflate(result);
decompresser.end();
System.out.printf(new String(result));

在实例化充气机时,boolen参数会发生魔力

BW休伯特

答案 2 :(得分:0)

对于心爱的Google员工,

如@dbw所述,

  

根据发布How to decompress stream deflated with java.util.zip.Deflater in .NET?,   java.util.zip.deflater equivalent in c#在C#中使用的默认放气机   没有任何Java等效项,因此用户偏爱Gzip,Ziplib   或其他一些zip技术。

一个相对简单的方法是使用GZip。 对于可接受的答案一个问题是,在这种方法中,您应该自己将数据大小附加到压缩字符串中,更重要的是根据我在生产应用程序中的经验,当字符串达到约2000个字符时,这是错误的!

该错误位于System.io.Compression.GZipStream

在c#中使用SharpZipLib的任何方式都可以解决问题,并且一切都将像下面的代码片段一样简单:

JAVA:

import android.util.Base64;

import com.google.android.gms.common.util.IOUtils;

import org.jetbrains.annotations.Nullable;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class CompressionHelper {

    @Nullable
    public static String compress(@Nullable String data) {
        if(data == null || data.length() == 0)
            return null;
        try {

            // Create an output stream, and a gzip stream to wrap over.
            ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
            GZIPOutputStream gzip = new GZIPOutputStream(bos);

            // Compress the input string
            gzip.write(data.getBytes());
            gzip.close();
            byte[] compressed;
            // Convert to base64
            compressed = Base64.encode(bos.toByteArray(),Base64.NO_WRAP);
            bos.close();
            // return the newly created string
            return new String(compressed);
        } catch(IOException e) {

            return null;
        }
    }


    @Nullable
    public static String decompress(@Nullable String compressedText) {
        if(compressedText == null || compressedText.length() == 0)
            return null;
        try {
            // get the bytes for the compressed string
            byte[] compressed = compressedText.getBytes("UTF-8");

            // convert the bytes from base64 to normal string
            compressed = Base64.decode(compressed, Base64.NO_WRAP);

            ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
            GZIPInputStream gis = new GZIPInputStream(bis);
            byte[] bytes = IOUtils.toByteArray(gis);
            return new String(bytes, "UTF-8");

        }catch (IOException e){
            e.printStackTrace();
        }

        return null;
    }

}

和c#:

using ICSharpCode.SharpZipLib.GZip; //PM> Install-Package SharpZipLib
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GeneralTools
{
    public static class CompressionTools
    {
        public static string CompressString(string text)
        {
            if (string.IsNullOrEmpty(text))
                return null;
            byte[] buffer = Encoding.UTF8.GetBytes(text);
            using (var compressedStream = new MemoryStream())
            {
                GZip.Compress(new MemoryStream(buffer), compressedStream, false);
                byte[] compressedData = compressedStream.ToArray();
                return Convert.ToBase64String(compressedData);
            }
        }


        public static string DecompressString(string compressedText)
        {
            if (string.IsNullOrEmpty(compressedText))
                return null;
            byte[] gZipBuffer = Convert.FromBase64String(compressedText);
            using (var memoryStream = new MemoryStream())
            {
                using (var compressedStream = new MemoryStream(gZipBuffer))
                {
                    var decompressedStream = new MemoryStream();
                    GZip.Decompress(compressedStream, decompressedStream, false);

                    return Encoding.UTF8.GetString(decompressedStream.ToArray()).Trim();
                }
            }
        }


    }

}

您还可以找到代码here