본문 바로가기
프로그래머/프로그래밍

apache-commons-net의 FTPClient 간단 사용법

by plog 2009. 9. 11.

- Commons net
Jakarta Commons의 net은 network utility collection

- 준비물
Commons net http://jakarta.apache.org/site/downloads/downloads_commons-net.cgi
Jakarta ORO http://jakarta.apache.org/site/downloads/downloads_oro.cgi

- reference
Commons net API http://jakarta.apache.org/commons/net/apidocs/index.html
Commons net http://jakarta.apache.org/commons/net/

- FTPClient 생성
FTPClient ftpClient = new FTPClient();

- FTPServer에 Connect
ftpClient.connect(server);

- 응답 상태 체크
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
    //  연결  종료
    ftpClient.disconnect();
    System.out.println("FTP server refused connection.");
}  else {

   // 정상처리

    ......
}

- FTP Server 로그인
ftpClient.login(username, password);

- FTP Server 로그아웃
ftpClient.logout();

- FTP Server disconnect
ftpClient.disconnect();

- example
FTPClient ftpClient = null;
try {
    ftpClient = new FTPClient();
    ftpClient.connect("111.111.111.111");   

   int reply = ftpClient.getReplyCode(); // 응답코드 체크

   if (!FTPReply.isPositiveCompletion(reply)) {
       ftpClient.disconnect();
       System.out.println("FTP server refused connection.");    
   } else {
       ftpClient.login(username, password); // 로긴 정보

       // 목록보기
       FTPFile[] ftpfiles = ftpClient.listFiles(); 

       if (ftpfiles != null) {
           for (int i = 0; i < ftpfiles.length; i++) {
               FTPFile file = ftpfiles[i];
               System.out.println(file.toString());  
           }
       }
       ftpClient.logout();
   }

} catch (Exception e) {
   e.printStackTrace();
} finally {
   if (ftpClient != null && ftpClient.isConnected()) {
    try {
         ftpClient.disconnect();
    } catch (IOException ioe) {
         ioe.printStackTrace();
    }
}
 
- example  (파일 다운로드)
    File get_file = new File("C:\\Test\\aaa.txt"); 
    OutputStream outputStream = new FileOutputStream(get_file);
    boolean result = ftpClient.retrieveFile("aaa.txt", outputStream); 
    outputStream.close();
 
- example (파일 업로드)
    File put_file = new File("C:\\Test\\aaa.txt");
    inputStream = new FileInputStream(put_file);
    boolean result = ftpClient.storeFile("aaa.txt", inputStream);
    inputStream.close();

- example  rename (파일 이름변경)
    boolean result = ftpClient.rename("befor.txt", "after.txt");
 
- example (파일삭제)
    boolean result = ftpClient.deleteFile("aaa.txt");

- example  파일 및 전송형태 설정
    파일 형태 설정
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

    파일 타입
    FTP.BINARY_FILE_TYPE, FTP.ASCII_FILE_TYPE, FTP.EBCDIC_FILE_TYPE,
    FTP.IMAGE_FILE_TYPE , FTP.LOCAL_FILE_TYPE 
    디폴트는 ASCII 이다

댓글