我正在尝试跟踪压缩进度. ATM我正在这样做:
public static void compressGzipTest(final OutputStream os, final File source) throws CompressorException,
IOException
{
final CountingInputStream cis = new CountingInputStream(new FileInputStream(source));
final GzipCompressorOutputStream gzipOut = (GzipCompressorOutputStream) new CompressorStreamFactory()
.createCompressorOutputStream(CompressorStreamFactory.GZIP,os);
new Thread() {
public void run()
{
try
{
long fileSize = source.length();
while (fileSize > cis.getBytesRead())
{
Thread.sleep(1000);
System.out.println(cis.getBytesRead() / (fileSize / 100.0));
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}.start();
IOUtils.copy(cis,gzipOut);
}
这可以正常工作,但是我需要线程,该线程给出的进度反馈不是在此方法中实现的,而是在调用它时(为了在android设备上创建进度条之类的东西).因此,这更像是一个体系结构问题.有什么想法,如何解决?
解决方法:
同时,我通过添加接口作为参数来覆盖IOUtils.copy()来解决此问题:
public static long copy(final InputStream input, final OutputStream output, int buffersize,
ProgressListener listener) throws IOException
{
final byte[] buffer = new byte[buffersize];
int n = 0;
long count = 0;
while (-1 != (n = input.read(buffer)))
{
output.write(buffer,0,n);
count += n;
listener.onProgress(n);
}
return count;
}
然后被这样的东西调用
copy(input, output, 4096, new ProgressListener() {
long totalCounter = 0;
DecimalFormat f = new DecimalFormat("#0.00");
@Override
public void onProgress(long bytesRead)
{
totalCounter += bytesRead;
System.out.println(f.format(totalCounter / (fileSize / 100.0)));
}
});
到目前为止,我面临的唯一挑战是限制控制台上的输出不是针对每个字节[4096],而是针对每个2兆字节.我尝试过这样的事情:
while (-1 != (n = input.read(buffer)))
{
output.write(buffer,0,n);
count += n;
while(n % 2097152 == 0)
{
listener.onProgress(n);
}
}
return count;
但这根本不给我任何输出