【问题标题】:Decompress string in java from compressed string in C#从 C# 中的压缩字符串解压缩 java 中的字符串
【发布时间】:2013-09-04 05:16:17
【问题描述】:

我正在寻找正确的解决方案来解压缩来自 c# 代码的 java 中的字符串。我尝试了很多 java 中的技术,例如(gzip、inflatter 等)。但没有得到解决方案。我得到了一些尝试从 c# 代码中的压缩字符串解压缩 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

【问题讨论】:

  • 请告诉我们您收到的错误信息。

标签: c# java gzip inflate compression


【解决方案1】:

我要压缩的 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;
}

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

【讨论】:

  • 谢谢@Deepak Bhatia,我尝试用你的java代码解压缩,我没有得到任何异常但它没有给出结果,它在这行代码后返回 GZIPInputStream gis = new GZIPInputStream(is , BUFFER_SIZE);.我无权更改 C# 中的压缩方法。所以我应该像在 C# 中一样。但在 java 中解压缩是行不通的。请帮助我
  • 对不起,我没有打印异常。现在它抛出 java.util.zip.ZipException: Not in GZIP format
  • 根据stackoverflow.com/questions/8490718/…、stackoverflow.com/questions/6522778/… 的帖子,C# 中使用的默认 deflater 没有任何 java 等效项,这就是用户更喜欢 Gzip、Ziplib 或其他一些 zip 技术的原因。但是,如果您发现有人发布答案,因为它也会帮助其他用户
  • 我面临着类似的问题 - java.util.zip.ZipException:不是 GZIP 格式。你能找到任何解决方案吗?
  • @Ashu 搞了好久了,能不能拿到上面贴的代码,看看能不能用......
【解决方案2】:

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

解决
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));

神奇的发生在实例化 Inflator 时的布尔参数

BW 休伯特

【讨论】:

    【解决方案3】:

    对于心爱的谷歌用户,

    正如@dbw 提到的,

    据How to decompress stream deflated with java.util.zip.Deflater in .NET?发帖, java.util.zip.deflater equivalent in c# C# 中使用的默认 deflater 没有任何 java 等价物,这就是为什么用户更喜欢 Gzip、Ziplib 或其他一些 zip 技术。

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

    错误在 System.io.Compression.GZipStream 中

    在 c# 中使用SharpZipLib 的任何方式问题都会消失,一切都会像以下 sn-ps 一样简单:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      相关资源
      最近更新 更多