자세 한 내용 은 JAVA 에서 FTPClient 도구 류 를 사용 하여 업로드 하고 다운로드 합 니 다.

14034 단어
자세 한 내용 은 JAVA 에서 FTPClient 도구 류 를 사용 하여 업로드 하고 다운로드 합 니 다.
자바 프로그램 에 서 는 FTP 서버 에 파일 을 업로드 하거나 파일 을 다운로드 하 는 등 FTP 와 자주 접촉 해 야 한다.이 글 은 jakarta comons 의 FTPClient (comons - net 패키지 에서) 를 이용 하여 다운로드 파일 을 업로드 하 는 방법 을 간단하게 소개 한다.
1. javabean 파일 을 작성 하여 ftp 가 업로드 하거나 다운로드 한 정 보 를 설명 합 니 다.
인 스 턴 스 코드:

public class FtpUseBean { 
  private String host; 
  private Integer port; 
  private String userName; 
  private String password; 
  private String ftpSeperator; 
  private String ftpPath=""; 
  private int repeatTime = 0;//  ftp       
   
  public String getHost() { 
    return host; 
  } 
   
  public void setHost(String host) { 
    this.host = host; 
  } 
 
  public Integer getPort() { 
    return port; 
  } 
  public void setPort(Integer port) { 
    this.port = port; 
  } 
   
   
  public String getUserName() { 
    return userName; 
  } 
   
  public void setUserName(String userName) { 
    this.userName = userName; 
  } 
   
  public String getPassword() { 
    return password; 
  } 
   
  public void setPassword(String password) { 
    this.password = password; 
  } 
 
  public void setFtpSeperator(String ftpSeperator) { 
    this.ftpSeperator = ftpSeperator; 
  } 
 
  public String getFtpSeperator() { 
    return ftpSeperator; 
  } 
 
  public void setFtpPath(String ftpPath) { 
    if(ftpPath!=null) 
      this.ftpPath = ftpPath; 
  } 
 
  public String getFtpPath() { 
    return ftpPath; 
  } 
 
  public void setRepeatTime(int repeatTime) { 
    if (repeatTime > 0) 
      this.repeatTime = repeatTime; 
  } 
 
  public int getRepeatTime() { 
    return repeatTime; 
  } 
 
  /** 
   * take an example:
* ftp://userName:password@ip:port/ftpPath/ * @return */ public String getFTPURL() { StringBuffer buf = new StringBuffer(); buf.append("ftp://"); buf.append(getUserName()); buf.append(":"); buf.append(getPassword()); buf.append("@"); buf.append(getHost()); buf.append(":"); buf.append(getPort()); buf.append("/"); buf.append(getFtpPath()); return buf.toString(); } }

2. 가방 commons - net - 1.4.1. jar 가 져 오기 

package com.util; 
 
import java.io.BufferedReader; 
import java.io.ByteArrayOutputStream; 
import java.io.DataOutputStream; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.net.SocketException; 
import java.net.URL; 
import java.net.URLConnection; 
 
import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory; 
import org.apache.commons.net.ftp.FTP; 
import org.apache.commons.net.ftp.FTPClient; 
import org.apache.commons.net.ftp.FTPClientConfig; 
import org.apache.commons.net.ftp.FTPFile; 
 
import com.bean.FtpUseBean; 
 
public class FtpUtil extends FTPClient { 
 
  private static Log log = LogFactory.getLog(FtpUtil.class); 
  private FtpUseBean ftpUseBean; 
  //              ,        size 
  private FTPFile[] files; 
     
  public FtpUseBean getFtpUseBean() { 
    return ftpUseBean; 
  } 
 
 
  public FtpUtil(){ 
    super(); 
  } 
   
   
  public void setFtpUseBean(FtpUseBean ftpUseBean) { 
    this.ftpUseBean = ftpUseBean; 
  } 
   
  public boolean ftpLogin() { 
    boolean isLogined = false; 
    try { 
      log.debug("ftp login start ..."); 
      int repeatTime = ftpUseBean.getRepeatTime(); 
      for (int i = 0; i < repeatTime; i++) { 
        super.connect(ftpUseBean.getHost(), ftpUseBean.getPort()); 
        isLogined = super.login(ftpUseBean.getUserName(), ftpUseBean.getPassword()); 
        if (isLogined) 
          break; 
      } 
      if(isLogined) 
        log.debug("ftp login successfully ..."); 
      else 
        log.debug("ftp login failed ..."); 
      return isLogined; 
    } catch (SocketException e) { 
      log.error("", e); 
      return false; 
    } catch (IOException e) { 
      log.error("", e); 
      return false; 
    } catch (RuntimeException e) { 
      log.error("", e); 
      return false; 
    } 
  } 
 
  public void setFtpToUtf8() throws IOException { 
 
    FTPClientConfig conf = new FTPClientConfig(); 
    super.configure(conf); 
    super.setFileType(FTP.IMAGE_FILE_TYPE); 
    int reply = super.sendCommand("OPTS UTF8 ON"); 
    if (reply == 200) { // UTF8 Command 
      super.setControlEncoding("UTF-8"); 
    } 
 
  } 
 
  public void close() { 
    if (super.isConnected()) { 
      try { 
        super.logout(); 
        super.disconnect(); 
        log.debug("ftp logout ...."); 
      } catch (Exception e) { 
        log.error(e.getMessage()); 
        throw new RuntimeException(e.toString()); 
      } 
    } 
  } 
 
  public void uploadFileToFtpByIS(InputStream inputStream, String fileName) throws IOException { 
    super.storeFile(ftpUseBean.getFtpPath()+fileName, inputStream); 
  } 
 
  public File downFtpFile(String fileName, String localFileName) throws IOException { 
    File outfile = new File(localFileName); 
    OutputStream oStream = null; 
    try { 
      oStream = new FileOutputStream(outfile); 
      super.retrieveFile(ftpUseBean.getFtpPath()+fileName, oStream); 
      return outfile; 
    } finally { 
      if (oStream != null) 
        oStream.close(); 
    } 
  } 
 
 
  public FTPFile[] listFtpFiles() throws IOException { 
    return super.listFiles(ftpUseBean.getFtpPath()); 
  } 
 
  public void deleteFtpFiles(FTPFile[] ftpFiles) throws IOException { 
    String path = ftpUseBean.getFtpPath(); 
    for (FTPFile ff : ftpFiles) { 
      if (ff.isFile()) { 
        if (!super.deleteFile(path + ff.getName())) 
          throw new RuntimeException("delete File" + ff.getName() + " is n't seccess"); 
      } 
    } 
  } 
 
  public void deleteFtpFile(String fileName) throws IOException { 
    if (!super.deleteFile(ftpUseBean.getFtpPath() +fileName)) 
      throw new RuntimeException("delete File" + ftpUseBean.getFtpPath() +fileName + " is n't seccess"); 
  } 
 
  public InputStream downFtpFile(String fileName) throws IOException { 
    return super.retrieveFileStream(ftpUseBean.getFtpPath()+fileName); 
  } 
 
  /** 
   * 
   * @return 
   * @return StringBuffer 
   * @description   ftp       ,addr         URL 
   */ 
  public StringBuffer downloadBufferByURL(String addr) { 
    BufferedReader in = null; 
    try { 
      URL url = new URL(addr); 
      URLConnection conn = url.openConnection(); 
      in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
      String line; 
      StringBuffer ret = new StringBuffer(); 
      while ((line = in.readLine()) != null) 
        ret.append(line); 
       
      return ret; 
    } catch (Exception e) { 
      log.error(e); 
      return null; 
    } finally { 
      try { 
        if (null != in) 
          in.close(); 
      } catch (IOException e) { 
        e.printStackTrace(); 
        log.error(e); 
      } 
    } 
  } 
 
  /** 
   * 
   * @return 
   * @return byte[] 
   * @description   ftp       ,addr         URL 
   */ 
  public byte[] downloadByteByURL(String addr) { 
     
    FTPClient ftp = null; 
     
    try { 
       
      URL url = new URL(addr); 
       
      int port = url.getPort()!=-1?url.getPort():21; 
      log.info("HOST:"+url.getHost()); 
      log.info("Port:"+port); 
      log.info("USERINFO:"+url.getUserInfo()); 
      log.info("PATH:"+url.getPath()); 
       
      ftp = new FTPClient(); 
       
      ftp.setDataTimeout(30000); 
      ftp.setDefaultTimeout(30000); 
      ftp.setReaderThread(false); 
      ftp.connect(url.getHost(), port); 
      ftp.login(url.getUserInfo().split(":")[0], url.getUserInfo().split(":")[1]); 
      FTPClientConfig conf = new FTPClientConfig("UNIX");   
           ftp.configure(conf);  
      log.info(ftp.getReplyString()); 
       
      ftp.enterLocalPassiveMode(); //ftp.enterRemotePassiveMode()  
      ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);  
 
      int reply = ftp.sendCommand("OPTS UTF8 ON");// try to 
       
      log.debug("alter to utf-8 encoding - reply:" + reply); 
      if (reply == 200) { // UTF8 Command 
        ftp.setControlEncoding("UTF-8"); 
      } 
      ftp.setFileType(FTPClient.BINARY_FILE_TYPE); 
 
      log.info(ftp.getReplyString()); 
       
      ByteArrayOutputStream out=new ByteArrayOutputStream(); 
           DataOutputStream o=new DataOutputStream(out); 
           String remotePath = url.getPath(); 
           /** 
           * Fixed:if doen't remove the first "/" at the head of url, 
            * the file can't be retrieved. 
           */ 
           if(remotePath.indexOf("/")==0) { 
             remotePath = url.getPath().replaceFirst("/", ""); 
           } 
           ftp.retrieveFile(remotePath, o);       
      byte[] ret = out.toByteArray(); 
      o.close(); 
       
      String filepath = url.getPath(); 
      ftp.changeWorkingDirectory(filepath.substring(0,filepath.lastIndexOf("/"))); 
      files = ftp.listFiles(); 
       
      return ret; 
        } catch (Exception ex) { 
      log.error("Failed to download file from ["+addr+"]!"+ex); 
       } finally { 
      try { 
        if (null!=ftp) 
          ftp.disconnect(); 
      } catch (Exception e) { 
        // 
      } 
    } 
    return null; 
//   StringBuffer buffer = downloadBufferByURL(addr); 
//   return null == buffer ? null : buffer.toString().getBytes(); 
  } 
   
   
   
   
  public FTPFile[] getFiles() { 
    return files; 
  } 
 
 
  public void setFiles(FTPFile[] files) { 
    this.files = files; 
  } 
 
 
// public static void getftpfilesize(String addr){ 
//    
//   FTPClient ftp = null; 
//    
//   try { 
//      
//     URL url = new URL(addr); 
//      
//     int port = url.getPort()!=-1?url.getPort():21; 
//     log.info("HOST:"+url.getHost()); 
//     log.info("Port:"+port); 
//     log.info("USERINFO:"+url.getUserInfo()); 
//     log.info("PATH:"+url.getPath()); 
//      
//     ftp = new FTPClient(); 
//      
//     ftp.setDataTimeout(30000); 
//     ftp.setDefaultTimeout(30000); 
//     ftp.setReaderThread(false); 
//     ftp.connect(url.getHost(), port); 
//     ftp.login(url.getUserInfo().split(":")[0], url.getUserInfo().split(":")[1]); 
//     FTPClientConfig conf = new FTPClientConfig("UNIX");   
//     ftp.configure(conf);  
//     log.info(ftp.getReplyString()); 
//      
//     ftp.enterLocalPassiveMode(); //ftp.enterRemotePassiveMode()  
//     ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);  
// 
//     int reply = ftp.sendCommand("OPTS UTF8 ON");// try to 
//      
//     log.debug("alter to utf-8 encoding - reply:" + reply); 
//     if (reply == 200) { // UTF8 Command 
//       ftp.setControlEncoding("UTF-8"); 
//     } 
//     ftp.setFileType(FTPClient.BINARY_FILE_TYPE); 
//     ftp.changeWorkingDirectory(url.getPath()); 
//     FTPFile[] files = ftp.listFiles(); 
//     for (FTPFile flie : files){ 
//       System.out.println(new String(flie.getName().getBytes("gbk"),"ISO8859-1")); 
//       System.out.println(flie.getSize()); 
//     } 
//      
// 
//   } catch (Exception ex) { 
//     log.error("Failed to download file from ["+addr+"]!"+ex); 
//   } finally { 
//     try {
     if (null!=ftp) 
//     ftp.disconnect(); 
 //     } catch (Exception e) { 
} 
} 
} 
}


이상 은 JAVA FTPClient 도구 류 의 업로드 와 다운로드 사례 에 대한 상세 한 설명 입 니 다. 궁금 한 점 이 있 으 시 면 댓 글 을 남기 거나 본 사이트 커 뮤 니 티 에 가서 토론 을 교류 하 십시오. 읽 어 주 셔 서 감사합니다. 도움 이 되 셨 으 면 좋 겠 습 니 다. 본 사이트 에 대한 지지 에 감 사 드 립 니 다!

좋은 웹페이지 즐겨찾기