java从ftp读取数据

 ftp读取数据,亲测有用

package info.lumanman.study;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTPUtil2 {
	static int ftpPort = 21;
	static String ftpUserName = "test";
	static String ftpPassword = "test1234";
	static String ftpHost = "127.0.0.1";
	static String ftpPath = "111,222,333,444";

	public static void readDataFromFTP(List> list){
		FTPClient ftp = new FTPClient();
		// ftp中文编码设置
	    ftp.setControlEncoding("GBK");
		FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
		conf.setServerLanguageCode("zh");
		ftp.configure(conf);
	    
	    try {
	    	ftp.connect(ftpHost, ftpPort);
			// 登录FTP服务器
	    	ftp.login(ftpUserName, ftpPassword);
			// 验证FTP服务器是否登录成功
			int replyCode = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(replyCode)) {
				return;
			}
			ftp.changeWorkingDirectory("user");//根目录文件夹名称
			// 获取文件集合
			FTPFile[] ftpFiles = ftp.listFiles();
			
			for (FTPFile file : ftpFiles) {
				if (file.isFile()) {// 如果是文件
						InputStream is = ftp.retrieveFileStream(file.getName());
						InputStreamReader isr = new InputStreamReader(is);
						BufferedReader br = new BufferedReader(isr);
						String ftpStr = "";
						String line = "";
						while ((line = br.readLine()) != null) {
							ftpStr += line + "\n";
						}
						// 解析ftpStr
						parseFTPStr(list, ftpStr);
				}
			}
	
	    } catch(IOException e) {
	      e.printStackTrace();
	    } finally {
	      if(ftp.isConnected()) {
	        try {
	          ftp.disconnect();
	        } catch(IOException ioe) {
	        }
	      }
	    }
	}

	public static void parseFTPStr(List> list, String ftpStr) {
		DateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
		String[] rows = ftpStr.split("\n");
		String zMerchantNo = "";
		//根据文件格式解析文件
		for (int i = 0; i < rows.length; i++) {
			if (i == 0) {
				zMerchantNo = rows[i].substring(2, 8);
				zMerchantNo = zMerchantNo.replace(" ", "");
			} else {
				// 获取对账平台数据到Map
				Map map = new HashMap();
				
				String zReqPayNo = rows[i].substring(0, 14);// 支付平台流水号
				zReqPayNo = zReqPayNo.replace(" ", "");// 去掉所有空格,包括首尾、中间
				
				map.put("zReqPayNo", zReqPayNo);
				map.put("zMerchantNo", zMerchantNo);

				// 将一行数据添加到list
				list.add(map);
			}
		}
	}

	public static void main(String[] args) throws Exception {
		// 存储FTP读取到的数据,以Map形式表示一行
		List> list = new ArrayList>();
		readDataFromFTP(list);
		for (Map map : list) {
			System.out.println(map.get("zUptranseq"));
		}
	}
}

 

你可能感兴趣的:(java从ftp读取数据)