ftp不能在java中正确下载文件?

itr*_*tro 7 java ftp connection

当我使用以下代码下载文件时,它只是将文件写入本地目标,但文件大小都为零.有人可以说为什么会发生这种情况以及如何解决这个问题?

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();
        }
    }

}
}
Run Code Online (Sandbox Code Playgroud)

itr*_*tro 17

在Apache文档中搜索后,我得出结论,BINARY_FILE_TYPE尚未解决.我添加了以下代码,一切正常.感谢所有帮助过你的人.

try {
    client.connect(ftpServer);
    client.login(username, password);
    // following line fixed my zip file corruption issue.
    client.setFileType(FTP.BINARY_FILE_TYPE);
Run Code Online (Sandbox Code Playgroud)