java httpclient 进度条_java – 如何使用Apache HttpClient 4获取文件上传的进度条?

我引入了一个派生的FileEntity,它只是对写入的字节进行计数。

它使用OutputStreamProgress进行实际计数(实际的OutputStream的装饰器的种类)。

这个(和一般的装饰)的优点是,我不需要复制实际的实现,如从文件流到输出流的实际复制。我也可以改变使用不同的(较新的)实现,像NFileEntity。

请享用…

FileEntity.java

public class FileEntity extends org.apache.http.entity.FileEntity {

private OutputStreamProgress outstream;

public FileEntity(File file, String contentType) {

super(file, contentType);

}

@Override

public void writeTo(OutputStream outstream) throws IOException {

this.outstream = new OutputStreamProgress(outstream);

super.writeTo(this.outstream);

}

/**

* Progress: 0-100

*/

public int getProgress() {

if (outstream == null) {

return 0;

}

long contentLength = getContentLength();

if (contentLength <= 0) { // Prevent division by zero and negative values

return 0;

}

long writtenLength = outstream.getWrittenLength();

return (int) (100*writtenLength/contentLength);

}

}

OutputStreamProgress.java

public class OutputStreamProgress extends OutputStream {

private final OutputStream outstream;

private volatile long bytesWritten=0;

public OutputStreamProgress(OutputStream outstream) {

this.outstream = outstream;

}

@Override

public void write(int b) throws IOException {

outstream.write(b);

bytesWritten++;

}

@Override

public void write(byte[] b) throws IOException {

outstream.write(b);

bytesWritten += b.length;

}

@Override

public void write(byte[] b, int off, int len) throws IOException {

outstream.write(b, off, len);

bytesWritten += len;

}

@Override

public void flush() throws IOException {

outstream.flush();

}

@Override

public void close() throws IOException {

outstream.close();

}

public long getWrittenLength() {

return bytesWritten;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值