K
K
Konstantin2014-07-03 20:17:06
Java
Konstantin, 2014-07-03 20:17:06

How to implement file upload from ftp server in java?

It is necessary to implement file upload from ftp server. To do this, I connected the Apache commons-net library and use this method:

public boolean downloadFromFTP(String fileName) throws IOException {
        FTPClient ftpClient = new FTPClient();

        ftpClient.connect(address, port);
        ftpClient.login(username, password);

        ftpClient.enterRemotePassiveMode();
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

        FileOutputStream fileOutputStream = new FileOutputStream("files/" + fileName);
        boolean isDownloaded = ftpClient.retrieveFile("/Test/" + fileName, fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
        ftpClient.logout();
        ftpClient.disconnect();

        return isDownloaded;
    }

The problem is that all uploaded files are 0 Kb each. Googled that this is a bug in the library, and it was supposedly fixed in version 3.0.1, but I use 3.2 (I even tried 3.3). How to get around this bug? Maybe someone has come across something similar.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Smirnov, 2014-07-04
@KChernenko

Most likely, the download operation failed and you didn't check for it. When errors occur, FTPClient does not throw an exception, but simply stores the error code, and the called method returns false. At the same time, the execution of the code continues and reaches the correct closing of the file, which is why you get a file with a size of 0 bytes. If retrieveFile returned false, then see ftpClient.getReplyString() instead of closing the file gracefully. For example, you can do this:

if(!isDownloaded) {
    throw new Exception(ftpClient.getReplyString());
}

At the same time, of course, do not forget about the release of resources in the finally block, which does not yet exist in the try block method ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question