java怎么连接ftp下载文件

   2024-10-22 7340
核心提示:在Java中连接FTP并下载文件,可以使用Apache Commons Net库。以下是一个简单的示例:import org.apache.commons.net.ftp.FTP;imp

在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库的依赖。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号