【发布时间】:2011-09-20 00:27:24
【问题描述】:
在 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:“行业标准算法”的这一段似乎是个笑话),而且非常残缺。除此之外,如果一次写入一个字节或以块的形式写入字节(这违背了“流”的概念),它的行为就会发生根本性的变化;如果我改变以上内容
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);
压缩变得(稍微)合理。耻辱。
【问题讨论】:
标签: c# java .net compression