有的时候需要用到java连接ftp服务器下载,上传一些操作,下面写了一个小例子。
/** ftp服务器地址 */
private String ftpHost;
/** ftp服务器用户名 */
private String ftpName;
/** ftp服务器密码 */
private String ftpPass;
/** ftp根目录 */
private String ftpDir;
/** 本地目录 */
private String localPath;
public boolean downloadFile(String path, String fileName) {// 全部路径String fullPath = path + fileName;FTPClient client = new FTPClient();// 超时client.setConnectTimeout(30000);File dir = new File(localPath + path);// 判断此文件夹是否存在if (!dir.exists())dir.mkdirs();try {// 连接ftpclient.connect(ftpHost);int replyCode = client.getReplyCode();if (!FTPReply.isPositiveCompletion(replyCode)) {client.disconnect();return false;}replyCode = client.getReplyCode();if (!FTPReply.isPositiveCompletion(replyCode)) {client.quit();return false;}// 登录if (client.login(ftpName, ftpPass)) {// 以2开头的返回值就会为真if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {client.disconnect();logger.error("连接ftp失败");}/** ftp server system type */FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_UNIX);/** server language */config.setServerLanguageCode("zh");/** server time zone */config.setServerTimeZoneId("Asia/Shanghai");/** ftp transfer mode in binary */client.setFileTransferMode(FTP.BINARY_FILE_TYPE);/** receive buffer size */client.setReceiveBufferSize(524288);client.configure(config);client.setFileTransferMode(FTP.BINARY_FILE_TYPE);client.setFileType(FTP.BINARY_FILE_TYPE);client.changeWorkingDirectory(ftpDir);// 转移到FTP服务器目录// 下载到本地return client.retrieveFile(ftpDir + fullPath, new FileOutputStream(localPath + fullPath));}} catch (Exception e) {e.printStackTrace();return false;} finally {if (client.isConnected()) {try {client.logout();} catch (IOException e) {e.printStackTrace();}}}return false;}
里面的具体参数可以根据情况来设置,是用的apache的开源项目。