java连接ftp下载

有的时候需要用到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 {
			// 连接ftp
			client.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的开源项目。

猜你喜欢

转载自286.iteye.com/blog/1170859
今日推荐