简体   繁体   English

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

[英]How to download file from FTP using Java?

With this code iI always get a empty file. 使用此代码,我总是得到一个空文件。
What I have to do with it? 我该怎么办?
login is always true . login始终为true (ofc, here is not real password) (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();
            }
        }
    }
}

Use something like this: 使用这样的东西:

InputStream inputStream = client.retrieveFileStream(remoteFileNameHere);

To retrieve the remote file input stream. 检索远程文件输入流。

Then you can use to copy the stream to desired file: 然后,您可以使用将流复制到所需文件:

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

Use FileOutputStream : 使用FileOutputStream

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM