Java:如何获得上传和下载速度 [英] Java: How to get upload and download speed
本文介绍了Java:如何获得上传和下载速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了一个程序将文件上传和下载到 FTP 服务器,但我无法监控速度和传输速率.
我使用了 FTPClient 类及其两个方法 retrievFile()
和 storeFile()
I write a program to upload and download files to FTP server but I can not monitor the speed and the transfer rate.
I used FTPClient class and its two methods retrievFile()
and storeFile()
推荐答案
试试这个:
public class ReportingOutputStream extends OutputStream {
public static final String BYTES_PROP = "Bytes";
private FileOutputStream fileStream;
private long byteCount = 0L;
private long lastByteCount = 0L;
private long updateInterval = 1L << 10;
private long nextReport = updateInterval;
private PropertyChangeSupport changer = new PropertyChangeSupport(this);
public ReportingOutputStream(File f) throws IOException {
fileStream = new FileOutputStream(f);
}
public void setUpdateInterval(long bytes) {
updateInterval = bytes;
nextReport = updateInterval;
}
@Override
public void write(int b) throws IOException {
byte[] bytes = { (byte) (b & 0xFF) };
write(bytes, 0, 1);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
fileStream.write(b, off, len);
byteCount += len;
if (byteCount > nextReport) {
changer.firePropertyChange( BYTES_PROP, lastByteCount, byteCount);
lastByteCount = byteCount;
nextReport += updateInterval;
}
}
@Override
public void close() throws IOException {
if (fileStream != null) {
fileStream.close();
fileStream = null;
}
}
public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
changer.removePropertyChangeListener(propertyName, listener);
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
changer.addPropertyChangeListener(propertyName, listener);
}
}
创建流后,为 BYTES_PROP
添加属性更改侦听器.默认情况下,它为每收到 1 KB 触发处理程序.调用 setUpdateInterval
进行更改.
After creating the stream, add a property change listener for BYTES_PROP
. By default it fires the handler for every 1 KB received. Call setUpdateInterval
to change.
这篇关于Java:如何获得上传和下载速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文