java 如何读取ftp服务器上的文件

java 如何读取ftp服务器上的文件

要在Java中读取FTP服务器上的文件,可以使用Java提供的FTPClient类来实现。以下是基本的代码示例:

import org.apache.commons.net.ftp.FTP;

import org.apache.commons.net.ftp.FTPClient;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

public class FTPExample {

public static void main(String[] args) {

String server = "ftp.example.com";

int port = 21;

String username = "your-username";

String password = "your-password";

String remoteFilePath = "/path/to/remote/file.txt";

String localFilePath = "/path/to/local/file.txt";

FTPClient ftpClient = new FTPClient();

try {

ftpClient.connect(server, port);

ftpClient.login(username, password);

ftpClient.enterLocalPassiveMode();

ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

// 下载文件

OutputStream outputStream = new FileOutputStream(localFilePath);

ftpClient.retrieveFile(remoteFilePath, outputStream);

outputStream.close();

System.out.println("文件下载成功!");

ftpClient.logout();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (ftpClient.isConnected()) {

try {

ftpClient.disconnect();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

上面的代码使用了Apache Commons Net库来处理FTP操作。首先,我们创建一个FTPClient实例并连接到FTP服务器。然后,使用login()方法进行身份验证。接下来,我们设置FTP客户端的模式和文件类型。在这个例子中,我们使用了被动模式和二进制文件类型。

为了下载文件,我们创建了一个用于写入本地文件的OutputStream。然后,使用retrieveFile()方法从远程FTP服务器下载文件,并将其写入本地文件中。

最后,我们使用logout()方法断开与FTP服务器的连接。

请注意,运行此代码需要导入Apache Commons Net库的依赖项。可以通过Maven或Gradle等构建工具进行导入。

希望这个示例能帮助您理解如何在Java中读取FTP服务器上的文件。如果有问题,请随时提问。

相关推荐