`
cping
  • 浏览: 31192 次
  • 性别: Icon_minigender_1
  • 来自: 合肥
社区版块
存档分类
最新评论

ftp文件读取上传

    博客分类:
  • java
 
阅读更多
读取ftp上文件,生成excel,再上传到ftp

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.base.util.DateUtils;
import com.ibatis.sqlmap.client.SqlMapClient;

public class Reconciliation {

	@Resource
	private SqlMapClient sqlMapClient;

	private static String ip = "*******";

	private static int port = 21;

	private static String userName = "***"; // 用户名

	private static String userPwd = "****"; // 密码

	public void reconciliation() throws IOException {
		InputStream fin = this.getClass().getClassLoader()
				.getResourceAsStream("template/reconciliation.xls");
		HSSFWorkbook wb = new HSSFWorkbook(fin);// 解析xls格式
		// 生成对账文件
		creatFile(wb);
	}

	/**
	 * 功能:Java读取txt文件的内容 步骤:1:先获得文件句柄 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
	 * 3:读取到输入流后,需要读取生成字节流 4:一行一行的输出。readline()。 备注:需要考虑的是异常情况
	 * 
	 * @param filePath
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void creatFile(HSSFWorkbook wb) {

		ArrayList list = new ArrayList();
		// 连接ftp服务器
		FTPClient ftpClient = connectServer(ip, port, userName, userPwd, null);
		int reply = ftpClient.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return;
		}
                /**这行要加上,FTPClient.enterLocalPassiveMode();这个方法的意思就
*是每次数据连接之前,ftp client告诉ftp server开通一个端口来传输数据。为什么要这样
*做呢,因为ftp server可能每次开启不同的端口来传输数据,但是在linux上或者其他服务器*上面,由于安全限制,可能某些端口没有开启,就会出现阻塞。
*/
		ftpClient.enterLocalPassiveMode();
 
		// 文件名称,当前日期前一天
		SimpleDateFormat sFormat = new SimpleDateFormat("yyyyMMdd");
		String fileName = "11610000" + sFormat.format(DateUtils.getLastDay());
		InputStream ins = null;
		BufferedReader reader = null;
		ByteArrayOutputStream os= null;
		try {
			// 从服务器上读取指定的文件
			ins = ftpClient.retrieveFileStream(fileName + ".cvs");
			reader = new BufferedReader(new InputStreamReader(ins, "GBK"));
			// 从第二行开始写数据
			int i = 1;
			String line;
			Sheet sheet = wb.getSheetAt(0);
			while ((line = reader.readLine()) != null) {
				creatRow(sheet, i, line);

				String[] textconten = line.split("\\|");
				Map param = new HashMap();
				param.put("TXNTM", textconten[1]);
				param.put("TXNAMT", textconten[4]);
				param.put("INSADR", textconten[11]);
				param.put("LOGNO", textconten[13]);
				int cnt = queryRecord(param);
				if (cnt == 0) {
					list.add(line);
				}
				i++;
			}

			// 主动调用一次getReply()把接下来的226消费掉. 这样做是可以解决这个返回null问题
			ftpClient.getReply();

			// 对账有差异的数据,写入到第二个sheet中
			writeSecondSheet(wb, list);
			
			// 设置为流传输
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			// 输出流转为输入流,上传到ftp
			os = new ByteArrayOutputStream();
			wb.write(os);
			byte[] b = os.toByteArray();
			ByteArrayInputStream in = new ByteArrayInputStream(b);
			
			ftpClient.storeFile(fileName + ".xls", in);   
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (ins != null) {
					ins.close();
				}
				if (reader != null) {
					reader.close();
				}
				if(os != null){
					os.close();
				}
				// 关闭ftp连接
				closeServer(ftpClient);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private int queryRecord(Map param) {
		int cnt = 0;
		try {
			cnt = (Integer) sqlMapClient.queryForObject(
					"selectCntReconciliation", param);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return cnt;
	}

	/**
	 * 对账有差异的数据,写入到第二个sheet中
	 * 
	 * @param wb
	 * @param list
	 */
	private void writeSecondSheet(Workbook wb, ArrayList list) {
		Sheet sheet = wb.getSheetAt(1);
		for (int i = 0; i < list.size(); i++) {
			creatRow(sheet, i + 1, (String) list.get(i));
		}
	}

	/**
	 * 每列数据
	 * 
	 * @param wb
	 * @param list
	 */
	private void creatRow(Sheet sheet, int i, String line) {
		Row row = sheet.createRow(i);
		String[] textconten = line.split("\\|");
		if (textconten != null) {
			for (int j = 0; j < textconten.length; j++) {
				String content = textconten[j];
				Cell cell = row.createCell(j);
				cell.setCellValue(content);
			}
		}
	}


	/**
	 * @param ip
	 * @param port
	 * @param userName
	 * @param userPwd
	 * @param path
	 * @throws SocketException
	 * @throws IOException
	 *             function:连接到服务器
	 */
	public FTPClient connectServer(String ip, int port, String userName,
			String userPwd, String path) {
		FTPClient ftpClient = new FTPClient();
		try {
			// 连接
			ftpClient.connect(ip, port);
			// 登录
			ftpClient.login(userName, userPwd);
			if (path != null && path.length() > 0) {
				// 跳转到指定目录
				ftpClient.changeWorkingDirectory(path);
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ftpClient;
	}

	/**
	 * @throws IOException
	 *             function:关闭连接
	 */
	public void closeServer(FTPClient ftpClient) {
		if (ftpClient.isConnected()) {
			try {
				ftpClient.logout();
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics