Java:如何获取上传和下载速度

标签 java streaming performance

我写了一个程序来上传和下载文件到 FTP 服务器,但我无法监控速度和传输速率。
我使用了 FTPClient 类及其两个方法 retrievFile()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 进行更改。

关于Java:如何获取上传和下载速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3140101/

相关文章:

linux - 如何通过 C 在 Linux(RPi) 中进行音频流处理?

mysql - 使用 mysql 连接表最快的方法是什么

java - 如何在JamVM中进行远程调试?

java - 访问静态变量

Azure 和直播

streaming - 如何下载 jwplayer 流媒体视频?

algorithm - 三重嵌套循环的复杂性

python - 大表上的连接查询非常慢(机器 = Xeon 2.4 GHz,16 核,64 GB RAM)

java - 无法读取控制台值 Java

java - 使用 Jetty 进行 LDAP 身份验证