gpt4 book ai didi

C# DeflateStream 与 Java DeflaterOutputStream

转载 作者:行者123 更新时间:2023-11-30 22:35:16 29 4
gpt4 key购买 nike

在 Java 中,这按预期工作:

  public static void testwrite(String filename) throws IOException {
FileOutputStream fs = new FileOutputStream(new File(filename), false);
DeflaterOutputStream fs2 = new DeflaterOutputStream(fs, new Deflater(3));
for (int i = 0; i < 50; i++)
for (int j = 0; j < 40; j++)
fs2.write((byte) (i + 0x30));
fs2.close();
}

public static void testread(String filename) throws IOException {
FileInputStream fs = new FileInputStream(new File(filename));
InflaterInputStream fs2 = new InflaterInputStream(fs);
int c, n = 0;
while ((c = fs2.read()) >= 0) {
System.out.print((char) c);
if (n++ % 40 == 0) System.out.println("");
}
fs2.close();
}

第一种方法将 2000 个字符压缩到一个 106 字节的文件中,第二种方法读取正常。

C# 中的等价物似乎是

private static void testwritecs(String filename) {
FileStream fs = new FileStream(filename, FileMode.OpenOrCreate);
DeflateStream fs2 = new DeflateStream(fs,CompressionMode.Compress,false);
for (int i = 0; i < 50; i++) {
for(int j = 0; j < 40; j++)
fs2.WriteByte((byte)(i+0x30));
}
fs2.Flush();
fs2.Close();
}

但它会生成一个 2636 字节的文件(比原始数据大,即使它具有低熵)并且无法使用上面的 Java testread() 方法读取。有什么想法吗?

已编辑:实现确实不是标准/可移植的(docs 的这一点:“行业标准算法”似乎是个笑话),而且非常残废。除其他外,如果一次写入一个字节或以 block 为单位写入字节(这与“流”的概念相悖),其行为将发生根本变化;如果我改变以上内容

for(int j = 0; j < 40; j++)
fs2.WriteByte((byte)(i+0x30));

通过

byte[] buf = new byte{}[40;
for(int j = 0; j < 40; j++)
buf[j]=(byte)(i+0x30));
fs2.Write(buf,0,buf.Length);

压缩变得(稍微)合理。耻辱。

最佳答案

不要在纯 ASCII 文本以外的任何内容上使用 DeflateStream,因为它使用为纯 ASCII 文本构建的静态定义的硬编码霍夫曼树。参见 my prior answer了解更多详情,或使用 SharpZipLib忘记它。

关于C# DeflateStream 与 Java DeflaterOutputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7478835/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com