首页主机资讯java怎么连接ftp下载文件

java怎么连接ftp下载文件

时间2024-05-29 04:48:03发布访客分类主机资讯浏览1401
导读:在Java中连接FTP并下载文件,可以使用Apache Commons Net库。以下是一个简单的示例: import org.apache.commons.net.ftp.FTP; import org.apache.commons.ne...

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

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: java怎么连接ftp下载文件
本文地址: https://pptw.com/jishu/670397.html
java怎么下载文件到指定文件夹 linux搭建ftp服务访问不了怎么解决

游客 回复需填写必要信息