使用 Apache Commons Net 编程,要了解文件或目录的详细信息,例如 FTP 服务器的大小和上次修改日期,可以调用 FTPClient 类的 mlistFile() 方法:
FTPFile ftpFile = ftpClient.mlistFile(remoteFilePath);
其中 remoteFilePath 是字符串,表示文件或目录的路径(可以相对于服务器上用户的主目录,也可以是绝对路径)。 如果指定的文件/目录存在,则方法返回 FTPFile 对象,否则返回 null。 然后,可以使用 FTPFile 类的 getter 方法来获取所需的信息:
String getGroup():获取拥有该文件的组的名称。
String getName():获取文件的名称。
String getRawListing():获取文件的服务器详细列表。
long getSize():获取文件大小(以字节为单位)。
Calendar getTimestamp():获取时间戳。
int getType():获取文件的类型。
String getUser():获取拥有该文件的用户的名称。
下面是示例程序,该程序登录到 FTP 服务器,然后调用 mlistFile() 方法获取文件的详细信息:
package org.91tech.ftp;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
/**
* An example program that demonstrates how to get details of a file and
* directory from a FTP server using Apache Commnons Net API.
*
*/
public class FTPGetFileDetails {
public static void main(String[] args) {
String server = "www.myserver.com";
int port = 21;
String user = "username";
String pass = "password";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
// use local passive mode to pass firewall
ftpClient.enterLocalPassiveMode();
// get details of a file or directory
String remoteFilePath = "Java/CodeLib/FTP.rar";
FTPFile ftpFile = ftpClient.mlistFile(remoteFilePath);
if (ftpFile != null) {
String name = ftpFile.getName();
long size = ftpFile.getSize();
String timestamp = ftpFile.getTimestamp().getTime().toString();
String type = ftpFile.isDirectory() ? "Directory" : "File";
System.out.println("Name: " + name);
System.out.println("Size: " + size);
System.out.println("Type: " + type);
System.out.println("Timestamp: " + timestamp);
} else {
System.out.println("The specified file/directory may not exist!");
}
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
}
运行上述程序时的输出:
Name: Java/CodeLib/FTP.rar
Size: 13021440
Type: File
Timestamp: Sat Jul 13 13:11:04 ICT 2013