java - Android 中的 FTP 下载速度极慢(仅在 Java 中速度很快)

标签 java android apache apache-commons ftp-client

我正在从 FTP 服务器下载 MP3 文件。它适用于将下载并播放 MP3 文件的 Android 应用程序。下载是使用 apache commons 库在 Java 中实现的,代码主要基于另一个教程。在我运行 Java 的桌面上下载速度非常快,下载一个大约 10mb 的文件大约需要 5 秒,但是在 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 上运行速度非常快,但在真实设备上却慢得令人痛苦。

所以,在调用下载函数retrieveFile之前 添加这样一行:

mFTPClient.setBufferSize(1024*1024);

关于java - Android 中的 FTP 下载速度极慢(仅在 Java 中速度很快),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14631639/

相关文章:

java - 如何解决 Heroku 上的 javax.net.ssl.SSLHandshakeException?

java - 设置一个用Java读取的阻塞文件

java - CLIENT-CERT auth-method 可以与 tomcat 中的 JDBC 域一起使用吗?

android - 分别触发 onFling 和 onScroll

apache - 重定向 Tomcat 上的所有请求

java - 从 unwrapped() 获得的 java ArrayList 转换为 Scala 列表

android - 如何在 onGeolocationPermissionsShowPrompt 中显示弹出窗口

android - 在android上获取免费进程内存

apache - .htaccess 中的数基转换

php - 如何使用 Apache、Php 和 Mysql 制作 "portable"web 应用程序?