java上传类 不指定

lanbingfeihan , 2010/01/31 21:20 , 编程和操作系统 , 评论(0) , 阅读(270) , Via 本站原创 | |
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[i].getName().equals(filename))continue;
        String name = fileList[i].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();
  }
}



发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]