linux系统ftp服务器 删除文件 java,在 Java 中如何删除 FTP 服务器上的文件 - Go语言中文社区

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();

}

}

}

}

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_29871897/article/details/115239074
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2023-01-02 19:57:25
  • 阅读 ( 286 )
  • 分类:Linux

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢