java實現讀取ftp伺服器上的csv檔案

來源:互聯網
上載者:User

標籤:server   filetype   get   遇到   nta   count   comm   setfile   desc   

定義ftp操作介面

import java.io.InputStream;import java.util.List;import org.apache.commons.net.ftp.FTPClient;/** * FTP伺服器操作*/public interface iFtpServU {    public FTPClient ftp(String ip, String user, String password);    public List<String[]> csv(InputStream in);}

介面實作類別

import java.io.IOException;import java.io.InputStream;import java.net.SocketException;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.List;import org.apache.commons.net.ftp.FTPClient;import org.apache.commons.net.ftp.FTPReply;import com.csvreader.CsvReader;/** * FTP伺服器操作具體實現*/public class FtpServUImpl implements iFtpServU {    /** 本地字元編碼 */    private static String LOCAL_CHARSET = "GBK";    // FTP協議裡面,規定檔案名稱編碼為iso-8859-1    private static String SERVER_CHARSET = "ISO-8859-1";    /**     *      * <b>登入ftp 返回ftpClient事件<b>     *      * @param ip     *            ftp所在ip     * @param user     *            登入名稱     * @param password     *            密碼     */    public FTPClient ftp(String ip, String user, String password) {        FTPClient ftpClient = new FTPClient();        try {            ftpClient.connect(ip);            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {                if (ftpClient.login(user, password)) {                    if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(                            "OPTS UTF8", "ON"))) {// 開啟伺服器對UTF-8的支援,如果伺服器支援就用UTF-8編碼,否則就使用本地編碼(GBK).                        LOCAL_CHARSET = "UTF-8";                    }                    ftpClient.setControlEncoding(LOCAL_CHARSET);                    ftpClient.enterLocalPassiveMode();// 設定被動模式                    // ftpClient.setFileType(getTransforModule());// 設定傳輸的模式                }            }            // ftpClient.login(user, password);        } catch (SocketException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        if (!ftpClient.isConnected()) {            ftpClient = null;        }        return ftpClient;    }    /**     * <b>將一個IO流解析,轉化數組形式的集合<b>     *      * @param in     *            檔案inputStream流     */    public List<String[]> csv(InputStream in) {        List<String[]> csvList = new ArrayList<String[]>();        if (null != in) {            CsvReader reader = new CsvReader(in, ‘,‘, Charset.forName("GBK"));            try {                // 遍曆每一行,若有#注釋部分,則不處理,若沒有,則加入csvList                while (reader.readRecord()) {                    if (!reader.getValues()[0].contains("#"))// 清除註釋部分                    {                        csvList.add(reader.getValues());                    }                }            } catch (IOException e) {                e.printStackTrace();            }            reader.close();        }        return csvList;    }}

業務情境中,調用ftp發生在對賬操作,使用者通過輸入交易筆數、csv檔案名稱,從而判斷ftp伺服器上是否存在該檔案,如果存在該檔案,則首先擷取檔案中的內容條數,與輸入的筆數數值比較,一致的話就繼續擷取csv檔案內容與系統資料庫中進行比較、對賬,從而完成對賬操作。

import java.io.InputStream;import java.util.List;import org.apache.commons.collections.CollectionUtils;import org.apache.commons.net.ftp.FTPClient;import org.apache.commons.net.ftp.FTPFile;//設定檔工具類import com.online.charge.customer.deployconfig.util.DeployConfigUtil;/** * @ClassName: QueryFtpFilesUtils * @Description: 擷取Ftp上檔案清單 * */public class QueryFtpFilesUtils {    /**     * 擷取Ftp用戶端     *      * @return     */    public static FTPClient getFtpClient() {        String ip = DeployConfigUtil.getInterfaceDeployConfig().getFtpUrl();        String userName = DeployConfigUtil.getInterfaceDeployConfig()                .getFtpUserName();        String userPassword = DeployConfigUtil.getInterfaceDeployConfig()                .getFtpPassword();        // 通過設定檔擷取ip,username,password        FTPClient ftpClient = getiFtpServU().ftp(ip, userName, userPassword);        return ftpClient;    }    /**     * 擷取ftp介面服務     *      * @return     */    private static iFtpServU getiFtpServU() {        return new FtpServUImpl();    }    /**     * 擷取明細條數     *      * @param fileName     *            csv檔案名稱 如:0320180908110523.csv 檔案的名稱為 0320180908110523     * @return 明細條數     */    public static Integer getFtpFileCount(String fileName) {        Integer count = 0;        boolean isContain = Boolean.FALSE;        FTPClient ftpClient = getFtpClient();        List<String[]> fileList = null;        if (null != ftpClient) {            try {                FTPFile[] file = ftpClient.listFiles();                if (file == null || file.length <= 0) {                    return -1;                }                // 遍曆所有檔案,匹配需要尋找的檔案                for (int i = 0; i < file.length; i++) {                    // 匹配到則進入                    if (file[i].getName().equals(fileName.concat(".csv"))) {                        isContain = Boolean.TRUE;                        // 將匹配到的檔案流傳入介面,轉化成數組集合                        InputStream in = ftpClient.retrieveFileStream(file[i].getName());                        fileList = getiFtpServU().csv(in);                        in.close();                    }                }                if (!isContain) {                    return -1;                }                if (CollectionUtils.isNotEmpty(fileList) && fileList.size() > 0) {                    count = fileList.size();                }            } catch (Exception e) {                e.printStackTrace();            }        }        return count;    }    /**     * 擷取FTP檔案內容     *      * @param fileName     * @return     */    public static void getFtpFileContent(String fileName,            List<String[]> fileContent) {        FTPClient ftpClient = getFtpClient();        if (null != ftpClient) {            try {                FTPFile[] file = ftpClient.listFiles();                // 遍曆所有檔案,匹配需要尋找的檔案                for (int i = 0; i < file.length; i++) {                    // 匹配到則進入                    if (file[i].getName().contains(fileName)) {                        InputStream in = ftpClient.retrieveFileStream(file[i].getName());                        fileContent.addAll(getiFtpServU().csv(in));                        in.close();                    }                }            } catch (Exception e) {                e.printStackTrace();            }        }    }}

在測試中,遇到能夠通過 listFiles方法擷取到ftp伺服器上的檔案清單,但調用 retrieveFileStream方法擷取檔案內容失敗(返回不是null),網上找了很多方法,嘗試都失敗,現總結如下:

// 匹配到則進入if (file[i].getName().equals(fileName.concat(Constant.ACCOUNT_FILE_EXTENDS_NAME))) {          isContain = Boolean.TRUE;// 1.設定主動模式//ftpClient.enterLocalPassiveMode();                                           // 2.檔案類型問題,設定檔案類型//ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // 3.編碼問題,設定編碼//InputStream in = ftpClient.retrieveFileStream(new String(file[i].getName().getBytes("UTF-8"),"ISO-8859-1"));InputStream in = ftpClient.retrieveFileStream(file[i].getName());// 將匹配到的檔案流傳入介面,轉化成數組集合  fileList = getiFtpServU().csv(in);  in.close();// 4.流關閉之後擷取返回狀態          //ftpClient.completePendingCommand();}

懷疑是 retrieveFileStream方法調用Socket擷取流中間出現的問題,但問題目前無法定位(讀者如果知道原因麻煩不吝賜教!)

為解決該問題,換了個思路:因為ftp上的檔案都有資料,且輸入的筆數都大於0,所以當確定ftp上確實有該檔案時,首先還是調用 retrieveFileStream方法以流的方式擷取該檔案,轉換為數組後判斷,如果長度為0,就說明擷取檔案內容失敗,此時換種方法:使用 retrieveFile方法將ftp伺服器上的檔案下載到本地,通過io流來擷取其內容。實現方法如下:

    // 匹配到則進入    if (file[i].getName().equals(fileName.concat(".csv"))) {        isContain = Boolean.TRUE;        // 將匹配到的檔案流傳入介面,轉化成數組集合        InputStream in = ftpClient.retrieveFileStream(file[i].getName());        fileList = getiFtpServU().csv(in);        in.close();        if(fileList.size() == 0){            //下載ftp檔案到本地            String osFileName = "G:/ftpFiles/"+file[i].getName();            File localFile = new File(osFileName);            OutputStream os = new FileOutputStream(localFile);            ftpClient.retrieveFile(file[i].getName() , os);            os.close();                        InputStream ins = new FileInputStream(new File(osFileName));            fileList = getiFtpServU().csv(ins);            ins.close();        }    }

 

java實現讀取ftp伺服器上的csv檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.