在 Java 中可以使用FTPClient类来实现对 FTP 服务器上文件的重命名操作。以下是示例代码:
import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
public class FTPRenameFile {
public static void main(String[] args) {
String server = "your_server_address";
int port = 21;
String username = "your_username";
String password = "your_password";
String oldFileName = "old_file_name";
String newFileName = "new_file_name";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(username, password);
boolean success = ftpClient.rename(oldFileName, newFileName);
if (success) {
System.out.println("文件重命名成功!");
} else {
System.out.println("文件重命名失败!");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
在上述代码中,你需要将your_server_address、your_username、your_password、old_file_name和new_file_name替换为实际的 FTP 服务器地址、用户名、密码、旧文件名和新文件名。
这段代码首先连接到 FTP 服务器,然后尝试使用rename方法对文件进行重命名。如果重命名成功,会输出相应的消息,否则输出重命名失败的消息。最后,无论操作是否成功,都会确保断开与 FTP 服务器的连接。