1. 程式人生 > >FTP上傳下載類

FTP上傳下載類

package com.test.ftp.impl;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
import ftp.FtpBean;
import ftp.FtpException;
import ftp.FtpListResult;
import ftp.FtpObserver;
**
* 檔案FTP下載上傳工具類
*
public class FtpUtil implements FtpObserver {
private final static Log logger = LogFactory.getLog(FtpUtil.class);
private FtpUtilParams ftpUtilParams;
FtpBean ftp;
long num_of_bytes_read = 0;
long num_of_bytes_write = 0;
public FtpUtil() {
ftp = new FtpBean();
}

**
 * 獲得Ftp伺服器當前目錄下有多少符合過濾條件的檔案
 *
 * @param path
 * @param host
 * @param username
 * @param password
 * @param filters
 *            副檔名陣列 例如:{"exe","txt"}
 * @return
 *
public long getFilterFtpFileCount(String path, String host,
        String username, String password, String[] filters)
        throws FtpException {
    try {
        ftp.ftpConnect(host, username, password);
    } catch (FtpException e) {
        throw new FtpException("連線ftp伺服器失敗,請確認ftp連線引數是否設定正確");
    } catch (IOException e) {
        throw new FtpException("連線ftp伺服器失敗," + e.getLocalizedMessage());
    }
    try {
        ftp.setDirectory(path);
        FtpListResult ftplrs = ftp.getDirectoryContent();
        long i = 0, j = 0;
        while (ftplrs.next()) {
            int type = ftplrs.getType();
            if (type == FtpListResult.FILE) {
                i++;
                String file = ftplrs.getName();
                int len = file.lastIndexOf(".");
                // 檔案有可能沒有副檔名,即沒有.,例如linux下的檔案,濾掉不處理
                if (len > 0) {
                    String tmpFile = file.substring(0, len);
                    // 對於用我們的FTP控制元件上傳的檔案,自動加了版本號,如.001,需要濾掉
                    if (tmpFile.lastIndexOf(".") > 0) {
                        file = tmpFile;
                    }
                }
                logger.debug("第" + i + "個檔案是:" + file);
                String[] splitFile = file.split("\\.");
                String extName = splitFile[splitFile.length - 1];
                logger.debug("第" + i + "個檔案字尾是:" + extName);
                if (isContainedFile(extName, filters)) {
                    j++;
                }
            }
        }
        logger.debug("檔案數量:" + i);
        logger.debug("符合過濾條件的檔案數量:" + j);
        return j;
    } catch (FtpException ex) {
        throw new FtpException("Ftp伺服器上沒有相應目錄");
    } catch (Exception e) {
        e.printStackTrace();
        throw new FtpException("目前系統還沒有上傳相關資料!");
    }
}

**
 * 判斷檔案的副檔名是否在要求的filter中
 *
 * @param extName
 * @param filters
 *            副檔名陣列 例如:{"exe","txt"}
 * @return
 *
private boolean isContainedFile(String extName, String[] filters) {
    boolean ret = false;
    // 如果沒有,則不過濾
    if (filters == null || filters.length < 1) {
        ret = true;
        return ret;
    }
    for (int i = 0; i < filters.length; i++) {
        if (extName.equalsIgnoreCase(filters[i])) {
            ret = true;
            break;
        }
    }
    return ret;
}
**
 * 刪除Ftp伺服器當前目錄下的所有檔案
 *
 * @param path
 * @param host
 * @param username
 * @param password
 * @throws FtpException
 *
public void deleteFtpFiles(String path, String host, String username,String password) throws FtpException {
    try {
        ftp.ftpConnect(host, username, password);
    } catch (FtpException e) {
        throw new FtpException("連線ftp伺服器失敗,請確認ftp連線引數是否設定正確");
    } catch (IOException e) {
        throw new FtpException("連線ftp伺服器失敗," + e.getLocalizedMessage());
    }
    try {
        ftp.setDirectory(path);
        FtpListResult ftplrs = ftp.getDirectoryContent();
        while (ftplrs.next()) {
            int type = ftplrs.getType();
            if (type == FtpListResult.FILE) {
                String filename = ftplrs.getName();
                ftp.fileDelete(filename);
            }
        }
    } catch (FtpException e) {
        throw e;
    } catch (IOException e) {
        throw new FtpException("IO異常");
    }
}
 * 下載檔案
 *
 * @param localeFile
 *            本地檔名
 * @param remoteFile
 *            遠端檔名
 * @param path
 *            Ftp登入後的相對路徑
 * @param host
 *            主機名
 * @param username
 *            使用者名稱
 * @param password
 *            密碼
 * @return 0 成功 1 失敗
 * @throws FileNotFoundException
 * @throws IOException
public static void downloadFile(String localeFile, String remoteFile,
        String path, String host, String username, String password)
        throws FtpException {
    FtpClient client = null;
    RandomAccessFile getFile = null;
    TelnetInputStream fget = null;
    DataInputStream puts = null;
    try {
        client = getConnect(path, host, username, password);
        int ch;
        File file = new File(localeFile);
        getFile = new RandomAccessFile(file, "rw");
        getFile.seek(0);
        fget = client.get(remoteFile);
        puts = new DataInputStream(fget);
        while ((ch = puts.read()) >= 0) {
            getFile.write(ch);
        }
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
        throw new FtpException("請確認檔案是否存在!");
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new FtpException("檔案讀取異常");
    } finally {
        try {
            if (fget != null)
                fget.close();
            if (getFile != null)
                getFile.close();
            if (client != null)
                client.closeServer();
        } catch (IOException e) {
            throw new FtpException("流關閉異常");
        }
    }
}
**
 * 把一個端伺服器上的檔案FTP到另一個伺服器.
 * 伺服器可以都是遠端伺服器
 *
public int ftpFileFromOneAddressToOtherAddress(FtpUtilParams transParam) throws FtpException {
    FtpClient origClient = null;
    FtpClient aimClient = null;
    TelnetInputStream fget = null;
    TelnetOutputStream out = null;
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("ftpParams ==" + transParam);
        }
        origClient = getConnect(transParam.getOrigPath(), transParam
                .getOrigHost(), transParam.getOrigUserName(), transParam
                .getOrigPassword());
        if (origClient == null) {
            return 1;
        }
        aimClient = getConnect(transParam.getAimPath(), transParam
                .getAimHost(), transParam.getAimUserName(), transParam
                .getAimPassword());
        if (aimClient == null) {
            return 1;
        }
        File file = new File(transParam.getAimFileName());
        fget = origClient.get(transParam.getOrigFileName());
        out = aimClient.put(file.getName());
        int c = 0;
        while ((c = fget.read()) != -1) {
            out.write(c);
        }
        return 1;
    } catch (FileNotFoundException ex) {
        throw new FtpException("請確認檔案是否存在!");
    } catch (IOException exp) {
        throw new FtpException("檔案讀取異常");
    } finally {
        try {
            if (out != null)
                out.close();
            if (fget != null)
                fget.close();
            if (aimClient != null)
                aimClient.closeServer();
            if (origClient != null)
                origClient.closeServer();
        } catch (IOException e) {
            throw new FtpException("流關閉異常");
        }
    }
}
**
 * FTP檔案到指定的伺服器上。(注意:如果是在廣域網上傳輸,此方法會有問題,不能上傳。)
 *
 * @param fileName
 *            上傳檔名
 * @param path
 *            Ftp登入後的相對路徑
 * @param host
 *            主機名
 * @param username
 *            使用者名稱
 * @param password
 *            密碼
 * @return 0 成功 1 失敗
 * @throws IOException
 * @throws FileNotFoundException
 *
public static int uploadFile(String fileName, String path, String host,
        String username, String password) throws FtpException {
    FtpClient client = getConnect(path, host, username, password);
    FileInputStream in = null;
    TelnetOutputStream out = null;
    if (client == null) {
        return 1;
    }
    try {
        File file = new File(fileName);
        in = new FileInputStream(file);
        out = client.put(file.getName());
        int c = 0;
        while ((c = in.read()) != -1) {
            out.write(c);
        }
        return 0;
    } catch (FileNotFoundException ex) {
        logger.debug("沒有要上傳的檔案,請確認!");
        return 1;
    } catch (IOException exp) {
        throw new FtpException("檔案讀取異常");
    } finally {
        try {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
            if (client != null)
                client.closeServer();
        } catch (IOException e) {
            throw new FtpException("流關閉異常");
        }
    }
}

 * @param path
 *            Ftp登入後的相對路徑
 * @param host
 *            主機名
 * @param username
 *            使用者名稱
 * @param password
 *            密碼
 * @return
 * @throws IOException

private static FtpClient getConnect(String path, String host,
        String username, String password) throws FtpException {
    try {
        FtpClient client = new FtpClient(host);
        client.login(username, password);
        client.binary();
        client.cd(path);
        return client;
    } catch (IOException ex) {
        throw new FtpException("連線ftp伺服器失敗,請確認ftp連線引數是否設定正確");
    }
}
// Implemented for FtpObserver interface.
// To monitor download progress.
public void byteRead(int bytes) {
    // num_of_bytes_read += bytes;
    // System.out.println(num_of_bytes_read + " of bytes read already.");
}
// Needed to implements by FtpObserver interface.
public void byteWrite(int bytes) {
    // num_of_bytes_write += bytes;
    // System.out.println(num_of_bytes_write + " of bytes read already.");
}
public FtpUtilParams getFtpUtilParams() {
    return ftpUtilParams;
}
public void setFtpUtilParams(FtpUtilParams ftpUtilParams) {
    this.ftpUtilParams = ftpUtilParams;
}

}
package com.test.ftp.impl;
**
* 這只是一個引數封裝類,用於傳遞引數到FtpUtil。
*
public class FtpUtilParams {
private String aimFileName;
private String origFileName;
private String aimPath;
private String origPath;
private String aimHost;
private String origHost;
private String aimUserName;
private String origUserName;
private String aimPassword;
private String origPassword;
public void setAimFileName(String aimFileName){
this.aimFileName = aimFileName;
}
public void setAimHost(String aimHost) {
this.aimHost = aimHost;
}
public void setAimPath(String aimPath) {
this.aimPath = aimPath;
}
public void setAimUserName(String aimUserName) {
this.aimUserName = aimUserName;
}
public void setOrigFileName(String origFileName) {
this.origFileName = origFileName;
}
public void setOrigHost(String origHost) {
this.origHost = origHost;
}
public void setAimPassword(String aimPassword) {
this.aimPassword = aimPassword;
}
public void setOrigPassword(String origPassword) {
this.origPassword = origPassword;
}
public void setOrigPath(String origPath) {
this.origPath = origPath;
}
public void setOrigUserName(String origUserName) {
this.origUserName = origUserName;
}
public String getAimFileName() {
return aimFileName;
}
public String getAimHost() {
return aimHost;
}
public String getAimPassword() {
return aimPassword;
}
public String getAimPath() {
return aimPath;
}
public String getAimUserName() {
return aimUserName;
}
public String getOrigFileName() {
return origFileName;
}
public String getOrigHost() {
return origHost;
}
public String getOrigPassword() {
return origPassword;
}
public String getOrigPath() {
return origPath;
}
public String getOrigUserName() {
return origUserName;
}

public String toString() {
    return  "  aimFileName = "+ aimFileName
    +"   ,origFileName ="+ origFileName
    +"   ,aimPath ="+ aimPath
    +"   ,origPath ="+ origPath
    +"   ,aimHost ="+ aimHost
    +"   ,origHost ="+ origHost
    +"   ,aimUserName ="+ aimUserName+"   ,origUserName ="+ origUserName
    +"   ,aimPassword ="+ aimPassword+"   ,origPassword ="+ origPassword;
}

}
package com.test.ftp.impl;
@SuppressWarnings(“serial”)
public class FtpException extends RuntimeException {
public FtpException() {
super();
}
public FtpException(String message) {
super(message);
}
public FtpException(String message, Throwable cause) {
super(message, cause);
}
public FtpException(Throwable cause) {
super(cause);
}
}