java怎么連接ftp下載文件

小億
237
2024-04-16 19:02:16

在Java中連接FTP并下載文件,可以使用Apache Commons Net庫(kù)。以下是一個(gè)簡(jiǎn)單的示例:

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

在這個(gè)示例中,我們首先創(chuàng)建一個(gè)FTPClient對(duì)象,并連接到指定的FTP服務(wù)器。然后使用login()方法登錄到FTP服務(wù)器,設(shè)置傳輸模式為二進(jìn)制文件類(lèi)型,然后使用retrieveFile()方法下載文件到本地文件中。最后,關(guān)閉FTP連接并輸出下載結(jié)果。

請(qǐng)注意,你需要確保在項(xiàng)目中包含Apache Commons Net庫(kù)的依賴。

0