如何从FTPserver获取文件列表?

众所周知,FTP是一种可靠的协议,用于在Internet上传输文件。虽然它不是一个安全协议,所有数据都以明文传输。但它是足够可靠的协议,可以通过互联网将数据从发送方发送到接收方。 这段代码涉及使用以下过程获取FTP服务器上所有您希望读取的文件的名称:

null
  • 在Java中,我们将使用 FTP客户 对象从FTP服务器读取文件。课程名为“组织”。阿帕奇。平民网ftp。FTPClient’需要导入以创建FTPClient的实例。
  • 这个 连接 ()方法调用FTPClient对象,以URL作为参数,与建立连接。
  • 使用 登录 ()方法发送凭据–用户名和密码。对于正确的凭据和成功登录,将返回true,这允许用户访问服务器上的文件。
  • 成功登录后,使用 列表名 ()方法获取当前工作目录中所有文件的名称。返回的列表将是一个数组,可以通过迭代读取名称。
  • 由于登录成功,因此需要 注销 ()读取完文件名后。最后是 断开 ()方法被调用以结束与连接的FTP服务器的关系。

// Java code to illustrate
// How to get a list of files from the FTPserver
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
public class MyFTPClass {
public static void main(String args[])
{
// Create an instance of FTPClient
FTPClient ftp = new FTPClient();
try {
// Establish a connection with the FTP URL
ftp.connect( "ftp.test.com" );
// Enter user details : user name and password
boolean isSuccess = ftp.login( "user" , "password" );
if (isSuccess) {
// Fetch the list of names of the files. In case of no files an
// empty array is returned
String[] filesFTP = ftp.listNames();
int count = 1 ;
// Iterate on the returned list to obtain name of each file
for (String file : filesFTP) {
System.out.println( "File " + count + " :" + file);
count++;
}
}
ftp.logout();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
ftp.disconnect();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}


本文由 里提卡 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享