English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

java에서 Apache 도구 집합을 사용하여 ftp 파일 전송 코드 설명

이 기사는 Apache 도구 집합 commons를 사용하는 방법을 주로 소개합니다.-net가 제공하는 ftp 도구는 ftp 서버에 파일 업로드 및 다운로드를 구현합니다.

1. 준비

commons를 참조해야 합니다-net-3.5.jar 패키지.

maven을 사용하여 가져오기:

<dependency>
  <groupId>commons-net</groupId>
  <artifactId>commons-net</artifactId>
  <version>3.5</version>
</dependency>

수동 다운로드:

https://ko.oldtoolbag.com/softs/550085.html

2. FTP 서버 연결

/**
   * FTP 서버에 연결
   * @throws IOException
   */
public static final String ANONYMOUS_USER="anonymous";
private FTPClient connect(){
	FTPClient client = new FTPClient();
	try{
		//FTP 서버에 연결
		client.connect(this.host, this.port);
		//로그인
		if(this.user==null||"".equals(this.user)){
			//익명 로그인 사용
			client.login(ANONYMOUS_USER, ANONYMOUS_USER);
		} else{
			client.login(this.user, this.password);
		}
		//파일 형식 설정
		client.setFileType(FTPClient.BINARY_FILE_TYPE);
		//FTP 서버 응답 가져오기
		int reply = client.getReplyCode();
		if(!FTPReply.isPositiveCompletion(reply)){
			client.disconnect();
			return null;
		}
		//작업 디렉토리 전환
		changeWorkingDirectory(client);
		System.out.println("===FTP에 연결됨: ");+host+:"+port);
	}
	catch(IOException e){
		return null;
	}
	return client;
}
/**
   * 작업 디렉토리 전환, 원격 디렉토리가 존재하지 않으면 디렉토리를 생성합니다.
   * @param client
   * @throws IOException
   */
private void changeWorkingDirectory(FTPClient client) throws IOException{
	if(this.ftpPath!=null&&!"".equals(this.ftpPath)){
		Boolean ok = client.changeWorkingDirectory(this.ftpPath);
		if(!ok){
			//ftpPath가 존재하지 않으면, 수동으로 디렉토리를 생성합니다.
			StringTokenizer token = new StringTokenizer(this.ftpPath,"\\",//");
			while(token.hasMoreTokens()){
				String path = token.nextToken();
				client.makeDirectory(path);
				client.changeWorkingDirectory(path);
			}
		}
	}
}
/**
   * FTP 연결 해제
   * @param ftpClient
   * @throws IOException
   */
public void close(FTPClient ftpClient) throws IOException{
	if(ftpClient!=null && ftpClient.isConnected()){
		ftpClient.logout();
		ftpClient.disconnect();
	}
	System.out.println("!!!FTP 연결 해제: ");+host+:"+port);
}

host: ftp 서버 IP 주소
port: ftp 서버 포트
user: 로그인 사용자
password: 로그인 비밀번호
로그인 사용자가 비어 있을 때, 익명 사용자로 로그인합니다.
ftpPath: ftp 경로, ftp 경로가 존재하지 않으면 자동으로 생성됩니다. 다중 층의 디렉토리 구조가 있을 경우, 디렉토리를 반복적으로 생성해야 합니다.

3. 파일 업로드

/**
   * 파일 업로드
   * @param targetName FTP에 업로드할 파일 이름
   * @param localFile 로컬 파일 경로
   * @return
   */
public Boolean upload(String targetName,String localFile){
	//연결 ftp server
	FTPClient ftpClient = connect();
	if(ftpClient==null){
		System.out.println("연결 FTP 서버["+host+:"+port+"]실패!");
		return false;
	}
	File file = new File(localFile);
	//업로드 후 파일 이름 설정
	if(targetName==null||"".equals(targetName))
	      targetName = file.getName();
	FileInputStream fis = null;
	try{
		long now = System.currentTimeMillis();
		//업로드 시작 파일
		fis = new FileInputStream(file);
		System.out.println(">>>업로드 시작 파일:"+file.getName());
		Boolean ok = ftpClient.storeFile(targetName, fis);
		if(ok){
			//업로드 성공
			long times = System.currentTimeMillis(); - now;
			System.out.println(String.format(">>>업로드 성공: 크기:%s, 업로드 시간:%d초", formatSize(file.length()), times/1000));
		} else//업로드 실패
		System.out.println(String.format(">>>업로드 실패: 크기:%s", formatSize(file.length())));
	}
	catch(IOException e){
		System.err.println(String.format(">>>업로드 실패: 크기:%s", formatSize(file.length())));
		e.printStackTrace();
		return false;
	}
	finally{
		try{
			if(fis!=null)
			          fis.close();
			ftpClient.close();
		}
		catch(Exception e){
		}
	}
	return true;
}

4. 파일 다운로드

/**
   * 파일 다운로드
   * @param localPath 로컬 저장 경로
   * @return
   */
public int download(String localPath){
	// 연결 ftp server
	FTPClient ftpClient = connect();
	if(ftpClient==null){
		System.out.println("연결 FTP 서버["+host+:"+port+"]실패!");
		return 0;
	}
	File dir = new File(localPath);
	if(!dir.exists())
	      dir.mkdirs();
	FTPFile[] ftpFiles = null;
	try{
		ftpFiles = ftpClient.listFiles();
		if(ftpFiles==null||ftpFiles.length==0)
		        return 0;
	}
	catch(IOException e){
		return 0;
	}
	int c = 0;
	for (int i=0;i<ftpFiles.length;i++{
		FileOutputStream fos = null;
		try{
			String name = ftpFiles[i].getName();
			fos = new FileOutputStream(new File(dir.getAbsolutePath()+File.separator+name));
			System.out.println("<<<파일 다운로드 시작:"+name);
			long now = System.currentTimeMillis();
			Boolean ok = ftpClient.retrieveFile(new String(name.getBytes("UTF-8"), "ISO-8859-1"), fos);
			if(ok){
				//다운로드 성공
				long times = System.currentTimeMillis(); - now;
				System.out.println(String.format("<<<다운로드 성공: 크기:%s, 업로드 시간:%d초", formatSize(ftpFiles[i].getSize()), times/1000));
				c++;
			} else{
				System.out.println("<<<다운로드 실패");
			}
		}
		catch(IOException e){
			System.err.println("<<<다운로드 실패");
			e.printStackTrace();
		}
		finally{
			try{
				if(fos!=null)
				            fos.close();
				ftpClient.close();
			}
			catch(Exception e){
			}
		}
	}
	return c;
}

파일 크기 정규화

private static final DecimalFormat DF = new DecimalFormat("#.##");
  /**
   * 파일 크기(비트, 킬로바이트, 메가바이트, گیگ바이트)를 정규화합니다
   * @param size
   * @return
   */
  private String formatSize(long size){
    if(size<1024{
      return size + " B";
    }1024*1024{
      return size/1024 + " KB";
    }1024*1024*1024{
      return (size/(1024*1024)) + " MB";
    } else {
      double gb = size/(1024*1024*1024);
      return DF.format(gb)+" GB";
    }
  }

5. 테스트

public static void main(String args[]){
    FTPTest ftp = new FTPTest("192.168.1.10",21,null,null,"/temp/2016/12");
    ftp.upload("newFile.rar", "D:/ftp/TeamViewerPortable.rar");
    System.out.println("");
    ftp.download("D:/ftp/");
  }

결과

=== FTP에 연결됨:192.168.1.10:21
>>> 파일 업로드 시작: TeamViewerPortable.rar
>>> 업로드 성공: 크기:5 MB, 업로드 시간:3초
!!! FTP 연결 끊기:192.168.1.10:21
=== FTP에 연결됨:192.168.1.10:21
<<< 파일 다운로드 시작: newFile.rar
<<< 다운로드 성공: 크기:5 MB, 업로드 시간:4초
!!! FTP 연결 끊기:192.168.1.10:21

결론

이것이 java가 Apache 도구 집합을 사용하여 ftp 파일 전송 코드를 구현한 전체 내용입니다. 많은 도움이 되었기를 바랍니다. 관심이 있는 분은 이 사이트의 다른 관련 주제를 참고할 수 있으며, 부족한 점이 있으면 댓글을 남겨 주시기 바랍니다. 이 사이트에 대한 지지를 감사합니다!

선언: 이 문서의 내용은 인터넷에서 가져왔으며, 저작권은 원저자에게 있으며, 인터넷 사용자가 자발적으로 기여하고 자체로 업로드한 내용입니다. 이 사이트는 소유권을 가지지 않으며, 인공 편집 처리를 하지 않았으며, 관련 법적 책임도 부담하지 않습니다. 저작권 침해가 의심되는 내용이 있으면 notice#w로 이메일을 보내 주시기 바랍니다.3codebox.com(보고할 때는 #을 @으로 변경하십시오.)를 통해 신고하시고 관련 증거를 제공하시면, 사실이 확인되면 이 사이트는 즉시 저작권 침해 내용을 삭제합니다.

추천 항목