我写了一个程序来上传和下载文件到 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/