主.java
import java.io.IOException;
public class Main
{
private final CompressedOutputStream m_cos;
public static void main(String[] args)
{
try
{
final Main m = new Main(new CompressedOutputStream());
m.run();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public Main(final CompressedOutputStream cos)
{
this.m_cos = cos;
}
private void trace(final String format, Object... args)
{
final String output = String.format(format, args);
System.out.println(output);
}
public void run()
{
this.first_write();
this.second_write();
this.trace("CRC32 of data is %x", this.m_cos.get_crc32());
}
private void add_data(final byte[] data)
{
try
{
this.m_cos.write(data); // STEPPING INTO THIS IN DEBUG DOESN'T LEAD ANYWHERE!
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void first_write()
{
final String[] text_lines = new String[] { "Hello world!",
"My name is Joe.", "Nice to meet.", "Where are you from?",
"I'm from Congo" };
for (final String text_line : text_lines)
{
final byte[] data = text_line.getBytes();
this.add_data(data);
}
final byte[] compressed_data = this.m_cos.get_compressed_data();
trace("Compressed data length (so far) is %d bytes",
compressed_data.length);
}
public void second_write()
{
final byte[] additional_data = new byte[] { 0x00, 0x01, 0x02, 0x03,
0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
this.add_data(additional_data);
final byte[] total_compressed_data = this.m_cos.get_compressed_data();
trace("Total compressed data length is %d bytes",
total_compressed_data.length);
}
}
CompressedOutputStream.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.GZIPOutputStream;
public class CompressedOutputStream extends GZIPOutputStream
{
private final ByteArrayOutputStream m_out;
public CompressedOutputStream() throws IOException
{
this(32);
}
public CompressedOutputStream(int size) throws IOException
{
super(new ByteArrayOutputStream(size), size);
this.m_out = (ByteArrayOutputStream) this.out;
this.def.setLevel(Deflater.BEST_COMPRESSION);
}
public long get_crc32()
{
return this.crc.getValue();
}
public byte[] get_compressed_data()
{
return this.m_out.toByteArray();
}
}
所以我有这段代码,它试图将 GZIPOutputStream 与 ByteArrayOutputStream 结合起来。
出于某种原因,我得到的只是相同的 10 个字节。
得到这个输出:
压缩数据长度(到目前为止)为 10 字节
总压缩数据长度为 10 字节
数据的 CRC32 为 4550d94d
似乎调用 write() 以抽象函数结束,即它没有到达任何地方,也没有写入任何内容。
我希望它在运行中被写入、压缩,并且能够在以后获取压缩的字节。
我在这里想念什么?似乎微不足道,但并非如此。
编辑#1:我的最终目标
只是澄清一下:最后我需要的是一个内存缓冲区,我将写入块中而不是序列中,并且在某个时候它达到X字节时我会能够获取这些压缩和校验和的字节(将它们写入某处,而不是标准的 Java 流)。