Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ftp doesn't download the file properly in java?

When i download file with following code it just write the file to destination on local but file size are all zero. Can anybody say Why this happen and how to fix it?

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import java.io.FileOutputStream;
import java.io.IOException;

public class FtpDownload {
public static void main(String[] args) {
    FTPClient client = new FTPClient();
    FileOutputStream fos = null;
    String filename = "config.zip";
    try {
        client.connect("ftpsrv");
        client.login("user", "user");

        for (FTPFile file : client.listFiles()) {
            filename = "C:\\tmp\\user\\" + file.getName();
            if (file.isFile()) {
                fos = new FileOutputStream(filename);
                client.retrieveFile(filename, fos);
                System.out.println(file.getName());
            } else if (file.isDirectory()) {
                System.out.println("directory: " + file.getName());
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
}
like image 915
itro Avatar asked Feb 29 '12 15:02

itro


1 Answers

after searching in the Apache documentation i come to conclusion that BINARY_FILE_TYPE is not yet settled. i have add following code and everything is OK. thanks to all of you that did help.

try {
    client.connect(ftpServer);
    client.login(username, password);
    // following line fixed my zip file corruption issue.
    client.setFileType(FTP.BINARY_FILE_TYPE);
like image 194
itro Avatar answered Nov 15 '22 22:11

itro