首页>>帮助中心>>香港云服务器java怎么连接ftp下载文件

香港云服务器java怎么连接ftp下载文件

2024/4/17 32次

香港云服务器Java中连接FTP并下载文件,可以使用Apache Commons Net库。以下是一个简单的示例:

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

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

import java.io.FileOutputStream;

import java.io.IOException;

public class FTPDownloader {

public static void main(String[] args) {

String server = "ftp.example.com";

String username = "username";

String password = "password";

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

String localFile = "local_file.txt";

FTPClient ftpClient = new FTPClient();

try {

ftpClient.connect(server);

ftpClient.login(username, password);

ftpClient.enterLocalPassiveMode();

ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

FileOutputStream outputStream = new FileOutputStream(localFile);

boolean success = ftpClient.retrieveFile(remoteFile, outputStream);

outputStream.close();

if (success) {

System.out.println("File downloaded successfully!");

} else {

System.out.println("Failed to download file!");

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (ftpClient.isConnected()) {

ftpClient.logout();

ftpClient.disconnect();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

复制代码

在这个示例中,我们首先创建一个FTPClient对象,并连接到指定的FTP服务器。然后使用login()方法登录到FTP服务器,设置传输模式为二进制文件类型,然后使用retrieveFile()方法下载文件到本地文件中。最后,关闭FTP连接并输出下载结果。

请注意,你需要确保在项目中包含Apache Commons Net库的依赖。

一诺网络香港免备案专区,提供「香港增强云服务器」和「香港特惠云服务器」两种类型的高可用弹性计算服务,搭载新一代英特尔®至强®铂金处理器,接入CN2低延时高速回国带宽线路,网络访问顺滑、流畅。机房网络架构采用了BGP协议的解决方案可提供多线路互联融合网络,使得不同网络运营商线路的用户都能通过最佳路由实现快速访问。香港云服务器低至29/月,购买链接:https://www.enuoidc.com/vps.html?typeid=2

版权声明

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们996811936@qq.com进行处理。