温馨提示×

java怎么连接ftp下载文件

小亿
84
2024-04-16 19:02:16
栏目: 编程语言

在Java中连接FTP并下载文件,可以使用Apache Commons Net库。以下是一个简单的示例:

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

import java.io.FileOutputStream;
import java.io.IOException;

public class FTPDownloader {

    public static void main(String[] args) {
        String server = "ftp.example.com";
        String username = "username";
        String password = "password";
        String remoteFile = "/path/to/remote/file.txt";
        String localFile = "local_file.txt";

        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(server);
            ftpClient.login(username, password);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            FileOutputStream outputStream = new FileOutputStream(localFile);
            boolean success = ftpClient.retrieveFile(remoteFile, outputStream);
            outputStream.close();

            if (success) {
                System.out.println("File downloaded successfully!");
            } else {
                System.out.println("Failed to download file!");
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

在这个示例中,我们首先创建一个FTPClient对象,并连接到指定的FTP服务器。然后使用login()方法登录到FTP服务器,设置传输模式为二进制文件类型,然后使用retrieveFile()方法下载文件到本地文件中。最后,关闭FTP连接并输出下载结果。

请注意,你需要确保在项目中包含Apache Commons Net库的依赖。

0