要使用 Apache Commons Net API 删除 FTP 服务器上的现有文件,可以调用 FTPClient 类的 deleteFile()方法:
public boolean deleteFile(String pathname) throws IOException
该方法将向 FTP 服务器发出 DELE 命令 删除指定的远程文件。 如果成功删除返回 true,否则返回 false(即,该文件不存在或为目录)。 在发生异常的情况下,如果与服务器的连接已经关闭,将引发 FTPConnectionClosedException 异常;如果在与服务器进行通信时发生 I/O错误,将引发 IOException 异常。
这是 deleteFile() 方法的用法示例:
FTPClient ftpClient = new FTPClient();
// code to connect and login...
String fileToDelete = "/Path/Of/File/To/Delete";
try {
boolean deleted = ftpClient.deleteFile(fileToDelete);
if (deleted) {
System.out.println("The file was deleted successfully.");
} else {
System.out.println("Could not delete the file.");
}
} catch (IOException ex) {
System.out.println("Oh no, there was an error: " + ex.getMessage());
}
// code to log out and disconnect...
为了说明 deleteFile() 方法的用法,下面提供了一个有效的示例程序,该程序:
1、登录到FTP服务器
2、删除服务器上的文件
3、注销并断开连接
下面是源代码:
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPDeleteFileDemo {
public static void main(String[] args) {
String server = "www.myserver.com";
int port = 21;
String user = "user";
String pass = "pass";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Connect failed");
return;
}
boolean success = ftpClient.login(user, pass);
if (!success) {
System.out.println("Could not login to the server");
return;
}
String fileToDelete = "/repository/video/cool.mp4";
boolean deleted = ftpClient.deleteFile(fileToDelete);
if (deleted) {
System.out.println("The file was deleted successfully.");
} else {
System.out.println("Could not delete the file, it may not exist.");
}
} catch (IOException ex) {
System.out.println("Oh no, there was an error: " + ex.getMessage());
ex.printStackTrace();
} finally {
// logs out and disconnects from server
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}