linux系统ftp服务器 删除文件 java,在 Java 中如何删除 FTP 服务器上的文件

要使用 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();

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值