如何使用Java从FTP下载文件?

时间:2015-03-05 09:05:22

标签: java ftp apache-commons-net

使用此代码,我总是得到一个空文件 我和它有什么关系?
login始终为true。 (ofc,这里不是真正的密码)

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.*;

public class Logs {
    public static void main(String[] args) {
        FTPClient client = new FTPClient();

        try {
            client.connect("myac.cs-server.pro", 121);
            boolean login = client.login("a3ro", "passWordIsSecret");
            System.out.println(login);
            String remoteFile1 = "myac_20150304.log";
            File downloadFile1 = new File("C:\\Users\\Aero\\Desktop\\test\\myac.log");
            OutputStream outputStream1 =
                new BufferedOutputStream(new FileOutputStream(downloadFile1));
            boolean success = client.retrieveFile(remoteFile1, outputStream1);
            System.out.println(success);
            outputStream1.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

使用类似的东西:

InputStream inputStream = client.retrieveFileStream(remoteFileNameHere);

检索远程文件输入流。

然后您可以使用将流复制到所需的文件:

 FileOutputStream out = new FileOutputStream(targetFile);
 org.apache.commons.io.IOUtils.copy(in, out);

答案 1 :(得分:1)

使用FileOutputStream

String filename = "test.txt";
FileOutputStream fos = new FileOutputStream(filename);
client.retrieveFile("/" + filename, fos);