1

我正在寻找正确的解决方案来解压缩来自 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。谢谢

4

3 回答 3

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;
}

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

于 2013-09-04T05:48:13.673 回答
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));

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

BW休伯特

于 2016-09-30T17:16:06.697 回答
0

对于心爱的谷歌用户,

正如@dbw 提到的,

根据帖子How to decompress stream deflated with java.util.zip.Deflater in .NET? , c# 中的java.util.zip.deflater 等效 C#中使用的默认 deflater 没有任何 java 等效项,这就是用户更喜欢 Gzip、Ziplib 或其他一些 zip 技术的原因。

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

该错误在 System.io.Compression.GZipStream

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

爪哇:

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();
                }
            }
        }


    }

}

你也可以在这里找到代码

于 2019-04-20T14:17:14.910 回答