共計 1192 個字符,預(yù)計需要花費 3 分鐘才能閱讀完成。
在 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();
}
}
}
}
在這個示例中,我們首先創(chuàng)建一個 FTPClient 對象,并連接到指定的 FTP 服務(wù)器。然后使用 login() 方法登錄到 FTP 服務(wù)器,設(shè)置傳輸模式為二進制文件類型,然后使用 retrieveFile() 方法下載文件到本地文件中。最后,關(guān)閉 FTP 連接并輸出下載結(jié)果。
請注意,你需要確保在項目中包含 Apache Commons Net 庫的依賴。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完