扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

java鎬庝箞杩炴帴ftp涓嬭浇鏂囦欢

扬州沐宇科技
2024-04-16 19:02:16
Java

鍦↗ava涓繛鎺TP骞朵笅杞芥枃浠讹紝鍙互浣跨敤Apache Commons Net搴撱€備互涓嬫槸涓€涓畝鍗曠殑绀轰緥锛?/p>

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

鍦ㄨ繖涓ず渚嬩腑锛屾垜浠鍏堝垱寤轰竴涓狥TPClient瀵硅薄锛屽苟杩炴帴鍒版寚瀹氱殑FTP鏈嶅姟鍣ㄣ€傜劧鍚庝娇鐢╨ogin()鏂规硶鐧诲綍鍒癋TP鏈嶅姟鍣紝璁剧疆浼犺緭妯″紡涓轰簩杩涘埗鏂囦欢绫诲瀷锛岀劧鍚庝娇鐢╮etrieveFile()鏂规硶涓嬭浇鏂囦欢鍒版湰鍦版枃浠朵腑銆傛渶鍚庯紝鍏抽棴FTP杩炴帴骞惰緭鍑轰笅杞界粨鏋溿€?/p>

璇锋敞鎰忥紝浣犻渶瑕佺‘淇濆湪椤圭洰涓寘鍚獳pache Commons Net搴撶殑渚濊禆銆?/p>

扫码添加客服微信