Java:如何获得上传和下载速度
我写了一个程序来上传和下载文件到FTP服务器,但我不能监控速度和传输速率。Java:如何获得上传和下载速度,java,streaming,performance,Java,Streaming,Performance,我写了一个程序来上传和下载文件到FTP服务器,但我不能监控速度和传输速率。 我使用了FTPClient类及其两个方法retrievFile()和storeFile(),因为retrieveFile和storeFile处理输入和输出流,您是否可以编写自己的子类来监视在特定时间内传入或传出的字节数?尝试一下: public class ReportingOutputStream extends OutputStream { public static final String BYTES_P
我使用了FTPClient类及其两个方法
retrievFile()
和storeFile()
,因为retrieveFile
和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);
}
}
公共类ReportingOutputStream扩展了OutputStream{
公共静态最终字符串字节\u PROP=“BYTES”;
私有文件输出流文件流;
专用长字节数=0L;
专用长lastByteCount=0L;
private long updateInterval=1L nextReport){
changer.firePropertyChange(字节数、最后字节数、字节数);
lastByteCount=字节数;
nextReport+=updateInterval;
}
}
@凌驾
public void close()引发IOException{
if(fileStream!=null){
fileStream.close();
fileStream=null;
}
}
public void removePropertyChangeListener(字符串propertyName,PropertyChangeListener侦听器){
changer.removePropertyChangeListener(propertyName,listener);
}
public void addPropertyChangeListener(字符串propertyName,PropertyChangeListener侦听器){
changer.addPropertyChangeListener(propertyName,listener);
}
}
创建流后,为字节\u PROP
添加属性更改侦听器。默认情况下,它每接收1 KB就触发一次处理程序。调用setUpdateInterval
进行更改