我正在尝试将以下 java 代码移植到 .net:
private final byte[] zipLicense(byte lic[])
{
byte buf[];
ByteArrayInputStream bis;
DeflaterInputStream dis;
ByteArrayOutputStream bos;
buf = new byte[64];
bis = new ByteArrayInputStream(lic);
dis = new DeflaterInputStream(bis, new Deflater());
bos = new ByteArrayOutputStream();
byte abyte0[];
int len;
while((len = dis.read(buf)) > 0)
bos.write(buf, 0, len);
abyte0 = bos.toByteArray();
try
{
bis.close();
dis.close();
bos.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
return abyte0;
}
我最好的尝试是这段 C# 代码:
private byte[] zipLicense(byte[] lic)
{
var outputMemStream = new MemoryStream();
ZipOutputStream zipStream;
using (zipStream = new ZipOutputStream(outputMemStream))
{
zipStream.Write(lic, 0, lic.Length);
Debug.WriteLine(string.Format("Compressed bytes: {0}", outputMemStream.Length));
}
return outputMemStream.ToArray();
}
ZipOutputStream 是 SharpZipLib 中的一个类
当我尝试运行 C# 代码时,第一次尝试写入 zipStream 时出现错误
zipStream.Write(lic, 0, lic.Length);
该错误表明我没有提供“无条目”。我在示例中看到,人们可以而且可能应该将一个条目字符串设置为 zip 流,但是什么 java 代码将其作为条目呢?请帮助将此 java 功能移植到 .Net。谢谢!
最佳答案
Java DeflaterInputStream
更像是 .NET 的 DeflateStream
。也就是说,它只是一个压缩流,没有完整 .zip 文件包含的目录索引。
试试这个:
private byte[] zipLicense(byte[] lic)
{
var outputMemStream = new MemoryStream();
using (DeflateStream stream =
new DeflateStream(outputMemStream, CompressionMode.Compress, true))
{
stream.Write(lic, 0, lic.Length);
}
Debug.WriteLine(string.Format("Compressed bytes: {0}", outputMemStream.Length));
return outputMemStream.ToArray();
}
请注意,我添加了对 Flush()
的调用。如果没有这个,outputMemStream.Length
属性可能不是当前的(即不完全是结果流的完整长度)。
就其值(value)而言,.NET 现在内置了相当好的 .zip 文件支持(例如 ZipArchive
类)。因此,如果您确实发现自己有一天确实需要它,我会尝试首先使用它,而不是在您的部署中添加第三方库。
关于java - 将 DeflaterInputStream 功能移植到 .net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27003374/