Android中的FTP下载速度非常慢(Java中速度很快)



我正在从FTP服务器下载MP3文件。它适用于将下载然后播放MP3文件的Android应用程序。下载是使用apache共享库在Java中实现的,代码主要基于另一个教程。下载在我运行 Java 的桌面上运行得非常快,大约需要 5 秒才能下载一个 ~10mb 的文件,但在 Android 设备上运行的相同代码(我尝试了 2 个)慢得离谱,需要 5-10 分钟下载相同的文件。(两个测试都是通过Wifi完成的)。

代码基于:http://androiddev.orkitra.com/?p=28&cpage=2#comment-40

下面的代码显示了使用的两种方法:连接和下载。

    public boolean connect(String host, String username, String pass, int port){
    try{
        mFTPClient.connect(host, port);
        if(FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
                boolean loginStatus = mFTPClient.login(username,  pass);
                mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
                mFTPClient.enterLocalPassiveMode();
                mFTPClient.setKeepAlive(true);
                return loginStatus;
        }

    } catch (Exception e){
        System.err.println("Error: Could not connect to: " + host);
        e.printStackTrace();
    }
    return false;
}
    public boolean download(String srcFilePath, String dstFilePath) {
    boolean downloadStatus = false;
    try {
        FileOutputStream dstFileStream = new FileOutputStream(dstFilePath);
        downloadStatus = mFTPClient.retrieveFile(srcFilePath,   dstFileStream);
        dstFileStream.close();
        return downloadStatus;
    } catch (Exception e) {
        System.err.println("Error: Failed to download file from " + srcFilePath + " to " + dstFilePath);
    }
    return downloadStatus;
}

希望我已经提到了所需的所有细节,如果有人能解释为什么它这么慢,以及我如何在合理的时间内下载它,我将不胜感激。

偶然

发现了类似的问题,通过更改下载缓冲区大小解决了它。

奇怪的是,相同的代码在Android模拟器x86上非常快,但在真实设备上却非常慢。

所以,在调用下载函数之前检索文件添加如下行:

mFTPClient.setBufferSize(1024*1024);
因此

,在调用下载函数之前,retrieveFile添加如下行:

mFTPClient.setBufferSize(1024*1024);

这是正确的解决方案。我的应用程序在 20 分钟内下载 10 个文件的速度很慢。对缓冲区进行此修改需要 1 分钟。和煦。谢谢。

最新更新