java怎么连接ftp下载文件

29次阅读
没有评论

共计 1192 个字符,预计需要花费 3 分钟才能阅读完成。

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

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-04-22发表,共计1192字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)