在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个字节文件中,第二个方法将其读取为ok。
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 ()方法读取。有什么想法吗?
编辑:这个实现确实不是标准/可移植的(这一点文档:“行业标准算法”似乎是个笑话),而且非常残缺。除其他外,如果一个人一次写一个字节或者用块写一个字节(这违背了“流”的概念),那么它的行为就会发生根本性的变化;如果我更改上面的内容的话。
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);压缩得到(稍微)合理。真丢人。
发布于 2011-09-20 00:48:24
除了普通的ASCII文本之外,不要在任何东西上使用DeflateStream,因为它使用为普通ASCII文本构建的静态定义、硬编码的Huffman树。有关更多细节,请参见我先前的回答,或者只需使用SharpZipLib并忘记它。
https://stackoverflow.com/questions/7478835
复制相似问题