How to download a file from FTP server to Android

2019-02-05 07:14发布

问题:

I have a requirement to download a image from FTP server to android device. I tried with few samples by using ftp4j-1.7.2.jar library, but failed to connect with FTP servers & messed up.

Have anyone worked with FTP servers?

Please suggest to make connection & download file from Server.

回答1:

Use library commons.apache.org/proper/commons-net

Check below code to download file from FTP server:

private Boolean downloadAndSaveFile(String server, int portNumber,
    String user, String password, String filename, File localFile)
    throws IOException {
FTPClient ftp = null;

try {
    ftp = new FTPClient();
    ftp.connect(server, portNumber);
    Log.d(LOG_TAG, "Connected. Reply: " + ftp.getReplyString());

    ftp.login(user, password);
    Log.d(LOG_TAG, "Logged in");
    ftp.setFileType(FTP.BINARY_FILE_TYPE);
    Log.d(LOG_TAG, "Downloading");
    ftp.enterLocalPassiveMode();

    OutputStream outputStream = null;
    boolean success = false;
    try {
        outputStream = new BufferedOutputStream(new FileOutputStream(
                localFile));
        success = ftp.retrieveFile(filename, outputStream);
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }

    return success;
} finally {
    if (ftp != null) {
        ftp.logout();
        ftp.disconnect();
    }
}
}


标签: android ftp