java获取服务器上的file对象_在 Java 中如何获取 FTP 服务器上文件或目录的详情...

使用 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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值