자바 연결 ftp 다운로드

2521 단어 자바
자바 로 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 의 오픈 소스 프로젝트 입 니 다.

좋은 웹페이지 즐겨찾기