Java 使用 FTPClient 判断文件是否存在 - 详细代码示例
"要判断FTP服务器上的文件是否存在,可以使用FTPClient的`listFiles`方法来获取文件列表,然后遍历列表来判断文件是否存在。\n\n下面是一个示例代码:\n\njava\nimport org.apache.commons.net.ftp.FTPClient;\nimport org.apache.commons.net.ftp.FTPFile;\n\npublic class FtpClientExample {\n\n public static void main(String[] args) {\n String server = \"ftp.example.com\";\n int port = 21;\n String user = \"username\";\n String password = \"password\";\n String remoteFilePath = \"/path/to/file.txt\";\n\n FTPClient ftpClient = new FTPClient();\n try {\n ftpClient.connect(server, port);\n ftpClient.login(user, password);\n\n FTPFile[] files = ftpClient.listFiles(remoteFilePath);\n if (files.length > 0) {\n System.out.println(\"File exists\");\n } else {\n System.out.println(\"File does not exist\");\n } \n\n ftpClient.logout();\n ftpClient.disconnect();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}\n\n\n在上面的示例中,我们创建了一个FTPClient对象,然后使用`connect`方法连接到FTP服务器,再使用`login`方法登录FTP服务器。\n\n接下来,我们使用`listFiles`方法获取指定路径的文件列表。如果返回的文件列表长度大于0,则说明文件存在;如果长度为0,则说明文件不存在。\n\n最后,我们使用`logout`方法登出FTP服务器,并使用`disconnect`方法断开连接。\n\n请确保你已经引入了Apache Commons Net库,这是一个常用的用于操作FTP的Java库。\n
原文地址: https://www.cveoy.top/t/topic/qeOf 著作权归作者所有。请勿转载和采集!