开发者

Java: How to get upload and download speed

开发者 https://www.devze.com 2023-01-04 22:19 出处:网络
I write a program to upload and download files to FTP server but I can not monitor the speed and the开发者_如何转开发 transfer rate.

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()


Give this a try:

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);
    }
}

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.


Since retrieveFile and storeFile deal with input and output streams, is it possible for you to write your own subclasses that can monitor the number of bytes transferred in or out over a certain time?

0

精彩评论

暂无评论...
验证码 换一张
取 消