2015-05-16 58 views
0

我正在使用Apache FTPClient在android设备和某个FTP服务器之间下载/上传文件。 我想测量下载和上传速度,单位为Mbps/KBps。如何使用Apache FTPClient测量上传/下载速度

上传,我的代码看起来是这样的:

// myFile is a path for local file inside my android device. 
InputStream inputStream = new FileInputStream(myFile); 
OutputStream outputStream = ftpclient.storeFileStream(remoteFile); 

byte[] bytesIn = new byte[4096]; 
int read = 0; 

while((read = inputStream.read(bytesIn)) != -1) { 
    outputStream.write(bytesIn, 0, read); 
} 

inputStream.close(); 
outputStream.close(); 

我知道两件事情是很重要的:

  1. 下载时,我所做的就是要总结个字节我已经读过while循环(使用inputStream.read(serverFile)返回值) 可以吗?它会反映下载速度吗?
  2. 对于上传,如何正确测量文件的上传速度?这个FTP客户端怎么做? 为我所知,outputStream.write()不会返回有用的值。 我的想法是在每次迭代(写入)后检查FTP服务器中文件的更新大小,但我不知道是否这是正确的/最简单的方法。还有如何用这个FTP客户端来实现它。

回答

0

我有一个简单的解决方案,但不是100%准确的,你可以通过增加更多的采样率来改善它。现在我只用一个样品,(TotalFileSize - CurrentByteTransferred /(CURRENTTIME - 开始时间))。您可以添加更多采样来改善结果。下面是代码示例:

更新上传统计这里

private final UploadStats uploadStats = new UploadStats(); 

private void updateUploadStats(long totalBytesTransferred, int bytesTransferred, long streamSize) { 
    long current = System.currentTimeMillis(); 

    synchronized (this.uploadStats) { 
     long timeTaken = (current - uploadStats.getStartTime()); 

     if (timeTaken > 1000L) { 
      uploadStats.setLastUpdated(current); 
      uploadStats.setEstimatedSpeed(totalBytesTransferred/(timeTaken/1000L)); 
     } 

     uploadStats.setTotalBytesTransferred(totalBytesTransferred); 
     uploadStats.setBytesTransferred(bytesTransferred); 
     uploadStats.setStreamSize(streamSize); 
    } 
} 

创建CopyStreamListener并追加到FTPClient

 CopyStreamAdapter copyStreamAdapter = new CopyStreamAdapter() { 
      @Override 
      public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) { 
       updateUploadStats(totalBytesTransferred, bytesTransferred, streamSize); 
      } 
     }; 

     FTPClient ftpClient = new FTPClient(); 
     ftpClient.connect(url); 

     if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { 
      ftpClient.disconnect(); 
      throw new Exception("Unable to connect."); 
     } 

     if (!ftpClient.login(username, password)) { 
      ftpClient.disconnect(); 
      throw new Exception("Failed to login."); 
     } 
     ftpClient.setCopyStreamListener(copyStreamListener); 
     ftpClient.setFileType(FTP.BINARY_FILE_TYPE); 
     ftpClient.enterLocalPassiveMode(); 
     ftpClient.storeFile(targetPath, inputFile); 
     ftpClient.logout(); 
     ftpClient.disconnect(); 

上传统计豆没有的getter/setter。有些是不相关的,可以跳过

这只是一个伪代码。如果您打算阅读并显示进度,则可以使用线程提高,因此同步关键字。