在 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();
}
第一种方法在 106 字节文件中压缩 2000 个字符,第二种方法可以正常读取。
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/