Ilya Gazman
Ilya Gazman

Reputation: 32226

Apache ftp.retrieveFileStream returns null

How to download a file from FTP using apache.commons, this what I been trying to do:

    ftp = new FTPClient();
    ftp.connect("my.remote");
    ftp.login("username", "password");

    String ftpPath = "/my/file/file.data";
    ftp.setFileTransferMode(FTPClient.BLOCK_TRANSFER_MODE);
    ftp.setFileType(FTP.BINARY_FILE_TYPE);
    System.out.println(ftp.mlistFile(ftpPath));
    InputStream inputStream = ftp.retrieveFileStream(ftpPath);
    if (inputStream == null) {
        System.out.println("Error " + " " + ftp.getReplyCode() +
        " " + ftp.getReplyString());
        return;
    }

But it gives me an error with the below output. It does work if I use FileZilla from the same machine

ype=file;Size=33130206;Modify=20170207225217;Perm=adfrw; file.data main
Error 500 500 Illegal PORT command

Upvotes: 2

Views: 2932

Answers (2)

Glu Tbl
Glu Tbl

Reputation: 31

It was happened to me also. After sometime i figured it out that my FTP server doesn't allow to download file. There was three option to choose in the server side 1)read 2)write 3) download. After I change the setting,it work flawlessly.

Before doing this, check if your ftp server support file downloading feature by simply browsing and downloading in some web browser.

Upvotes: 0

Liz Lamperouge
Liz Lamperouge

Reputation: 681

first of all, are you sure is FTP and not FTPS? A part of this, try to use this code:

ftp = new FTPClient();
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
    int reply;
    ftp.connect(host,numPort); //if you have not port number, use only host
    reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        System.out.println("Error");
    }
    ftp.login(user, pwd);
    ftp.setFileType(ftp.BINARY_FILE_TYPE);
    ftp.enterLocalPassiveMode();
    ftp.printWorkingDirectory(); //print workingdirectory
    ftp.changeWorkingDirectory("/work"); //change directory
    ftp.printWorkingDirectory();
    FTPFile[] files1 = ftp.listFiles();
    for (FTPFile file : files) {
        String details = file.getName();
        Calendar dateOfmyFile=file.getTimestamp();
        boolean isaDir=false;
        if (file.isDirectory()) {
            details = "[" + details + "]";
            isaDir=true;
        }
        else{
           downloadFile(host+details, mylocalFilePath);
          }
       }
public void downloadFile(String remoteFilePath, String localFilePath) throws IOException {
    FileOutputStream fos = null;
    ftp.printWorkingDirectory();
    try {
        fos =new FileOutputStream(localFilePath);
        ftp.retrieveFile(remoteFilePath,fos);
        fos.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

Upvotes: 3

Related Questions