ftp不能在java中正确下载文件? [英] ftp doesn't download the file properly in java?

查看:555
本文介绍了ftp不能在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();
        }
    }

}
}


推荐答案

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

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

这篇关于ftp不能在java中正确下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆