要連接Java FTP服務器,您需要使用一個支持FTP協議的庫,例如Apache Commons Net。以下是一個簡單的示例,說明如何使用Java連接到FTP服務器并執行一些基本操作:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.8.0</version>
</dependency>
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.IOException;
public class FTPServerExample {
public static void main(String[] args) {
String server = "your_ftp_server_address";
int port = 21; // FTP默認端口為21
String user = "your_username";
String pass = "your_password";
FTPClient ftpClient = new FTPClient();
try {
// 連接到FTP服務器
ftpClient.connect(server, port);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Connect failed");
return;
}
// 登錄到FTP服務器
boolean isLoggedIn = ftpClient.login(user, pass);
if (!isLoggedIn) {
System.out.println("Login failed");
return;
}
// 切換到另一個目錄(例如:/home/user)
String remoteDirectory = "/home/user";
boolean isDirectoryChanged = ftpClient.changeWorkingDirectory(remoteDirectory);
if (!isDirectoryChanged) {
System.out.println("Failed to change directory");
return;
}
// 上傳文件到FTP服務器
String localFilePath = "path/to/your/local/file.txt";
String remoteFilePath = "path/to/your/remote/file.txt";
boolean isFileUploaded = ftpClient.storeFile(remoteFilePath, new java.io.File(localFilePath));
if (!isFileUploaded) {
System.out.println("Failed to upload file");
return;
}
System.out.println("File uploaded successfully");
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
// 斷開與FTP服務器的連接
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
請確保將your_ftp_server_address、your_username、your_password、path/to/your/local/file.txt和path/to/your/remote/file.txt替換為實際的FTP服務器地址、用戶名、密碼以及本地文件和遠程文件的路徑。
這個示例展示了如何連接到FTP服務器、登錄、切換目錄、上傳文件以及斷開連接。您可以根據需要執行其他操作,例如下載文件、刪除文件等。