java鎬庝箞杩炴帴ftp涓嬭浇鏂囦欢
鍦↗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>
相关问答