古8382 发表于 2016-6-8 06:16:29

ftp上传源码

  
  import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
  import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;
  
  
public class FtpService extends BaseServiceSupport {
 
  public static FTPClient ftpClient;
 
  /**  连接服务器
   * 
   *  */
  private void connect() {
 
    try {
      String server = Configuration.getInstance().getFtpServerIp();
      String username = Configuration.getInstance().getFtpServerUsername();
      String password = Configuration.getInstance().getFtpServerPassword();
      ftpClient = new FTPClient();
      ftpClient.connect(server);
      ftpClient.login(username, password);
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * 关闭连接
   */
  public void closeConnect() {
    try {
      ftpClient.disconnect();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
  
  /**
   * 上传
   *
   */
  public void upload(InputStream is,String filename) {
    try {
        String destFileName = filename;
        String tempFileName = "tmp_" + filename;
        boolean flag = ftpClient.storeFile(tempFileName, is);
        if (flag) {
          ftpClient.rename(tempFileName, destFileName);
        }
        is.close();
      }
    catch (IOException e) {
     e.printStackTrace();
    }
  }
  /**
   * 从服务器下载文件到本地
   */
  public void download(String filepath,String filename) {
    try {
      FTPFile[] fileList = ftpClient.listFiles();
      for (int i = 0; i < fileList.length; i++){
     if(fileList.getName().equals(filename))continue;
        String name = fileList.getName();
        File tempFile = new File(filepath + filename);
        File destFile = new File(filepath + filename);
        FileOutputStream fos = new FileOutputStream(tempFile);
        boolean flag = ftpClient.retrieveFile(name, fos);
        // 关闭文件流
        fos.close();
        if (flag) {
         tempFile.renameTo(destFile);
        }
      }
    }
    catch (IOException e){
     e.printStackTrace();
    }
  }
  /** 
   * 测试函数
   * @throws FileNotFoundException 
   */
  public static void main(String[] args) throws FileNotFoundException{
    FtpService fd = new FtpService();
    fd.connect();
    File file = new File("d:/logfile.log");
    InputStream in  = new FileInputStream(file);
    fd.upload(in,"logfile.log");
    fd.closeConnect();
  }
}
  
页: [1]
查看完整版本: ftp上传源码