ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

android-跟踪复制文件的进度

2019-10-30 00:33:33  阅读:266  来源: 互联网

标签:progress compression android


我正在尝试跟踪压缩进度. 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;

但这根本不给我任何输出

标签:progress,compression,android
来源: https://codeday.me/bug/20191030/1964185.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有