栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用进度回调将文件或InputStream上载到S3

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用进度回调将文件或InputStream上载到S3

我遇到了这个确切的问题,并编写了一个简单的InputStream包装器,该包装器输出了不错的进度条:

import java.io.IOException;import java.io.InputStream;import org.apache.commons.vfs.FileContent;import org.apache.commons.vfs.FileSystemException;public class ProgressInputStream extends InputStream {    private final long size;    private long progress, lastUpdate = 0;    private final InputStream inputStream;    private final String name;    private boolean closed = false;    public ProgressInputStream(String name, InputStream inputStream, long size) {        this.size = size;        this.inputStream = inputStream;        this.name = name;    }    public ProgressInputStream(String name, FileContent content)    throws FileSystemException {        this.size = content.getSize();        this.name = name;        this.inputStream = content.getInputStream();    }    @Override    public void close() throws IOException {        super.close();        if (closed) throw new IOException("already closed");        closed = true;    }    @Override    public int read() throws IOException {        int count = inputStream.read();        if (count > 0) progress += count;        lastUpdate = maybeUpdateDisplay(name, progress, lastUpdate, size);        return count;    }    @Override    public int read(byte[] b, int off, int len) throws IOException {        int count = inputStream.read(b, off, len);        if (count > 0) progress += count;        lastUpdate = maybeUpdateDisplay(name, progress, lastUpdate, size);        return count;    }    static long maybeUpdateDisplay(String name, long progress, long lastUpdate, long size) {        if (Config.isInUnitTests()) return lastUpdate;        if (size < B_IN_MB/10) return lastUpdate;        if (progress - lastUpdate > 1024 * 10) { lastUpdate = progress; int hashes = (int) (((double)progress / (double)size) * 40); if (hashes > 40) hashes = 40; String bar = StringUtils.repeat("#",         hashes); bar = StringUtils.rightPad(bar, 40); System.out.format("%s [%s] %.2fMB/%.2fMBr",         name, bar, progress / B_IN_MB, size / B_IN_MB); System.out.flush();        }        return lastUpdate;    }}

(这是从实时代码中复制粘贴的,因此您可能必须做一些修补才能使其在您自己的代码中起作用。)

然后,只需使用InputStream放置内容的方式(确保指定大小!),它将为您提供一个不错的进度条。如果您想要适当的回调,那也很容易做到。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/438246.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号