filecsvhelper.java

来自「项目支付宝批量打款,采用httpclient+spring +quarz实现.」· Java 代码 · 共 348 行

JAVA
348
字号
package com.szhelper.pay.quartz.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.szhelper.pay.model.DownloadPayBean;

/**
 * 
 * @author Fang
 * @version 1.0
 * @date 2008-08-07
 */
public class FileCSVHelper {
	private static Log logger = LogFactory.getLog(FileCSVHelper.class);
	private boolean convertFlag = false;
	public static final String DEL_CHAR = ",";
	public static final String AV_CHAR = "\"";
	private FileOutputStream fos = null;
	private StringBuffer sb = null;

	private InputStreamReader fr = null;
	private List dataContainer = new ArrayList();

	/** *********************创建CSV文件***************************** */

	public void initGenerateCSVFile(String file) {
		try {
			fos = new FileOutputStream(file, false);
			sb = new StringBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String CSVEncode(String in) {
		if (in == null)
			return "";
		in.replaceAll("&", "&");
		in.replaceAll("\"", """);
		return in;
	}

	public String CSVDecode(String in) {
		if (in == null)
			return "";
		in.replaceAll(""", "\"");
		in.replaceAll("&", "&");
		return in;
	}

	public void setData(String data) {
		if (convertFlag)
			data = CSVEncode(data);
		sb.append(AV_CHAR);
		sb.append(data);
		sb.append(AV_CHAR);
		sb.append(DEL_CHAR);
	}

	public void setConvertFlag(boolean b) {
		convertFlag = b;
	}

	public void writeLine() {
		if (sb.charAt(sb.length() - 1) == ',')
			sb.delete(sb.length() - 1, sb.length());
		sb.append("\r\n");
	}

	public void writeDataByLine(String[] args) {
		for (int i = 0; i < args.length; i++)
			setData(args[i]);
		writeLine();
	}

	public void close() throws IOException {
		try {
			if (fos != null)
				fos.write(sb.toString().getBytes());
		} catch (IOException e) {
			throw e;
		} finally {
			if (fos != null)
				fos.close();
			if (fr != null)
				fr.close();
		}
	}

	/** *********************解析CSV文件***************************** */
	public void initAnalyzeCSVFile(String file) throws IOException {
		fr = new InputStreamReader(new FileInputStream(file));
	}

	private ArrayList analysisLine(String strLine) {
		System.out.println(strLine);
		ArrayList al = new ArrayList();
		String[] dataArr = strLine.split(AV_CHAR);
		for (int i = 1; i < dataArr.length; i = i + 2) {
			if (convertFlag)
				al.add(CSVDecode(dataArr[i]));
			else
				al.add(dataArr[i]);
		}
		return al;
	}

	/** *********************通常的做法***************************** */
	public static boolean generateCSVFile(String file, String data) {
		logger.info("generating csv file ...");
		boolean success = true;
		FileWriter fw = null;
		try {
			fw = new FileWriter(file, false);
			fw.write(data);
			logger.info("csv file is generated successfully.");
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e);
			success = false;
		} finally {
			try {
				if (fw != null)
					fw.close();
			} catch (IOException e) {
				e.printStackTrace();
				logger.error(e);
			}
		}
		return success;
	}
	
	public static String loadCSVFile(String file) {
		StringBuffer content = new StringBuffer();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(file));
			String line = br.readLine();
			while(line != null){
				content.append(line);
				line = br.readLine();
			}	
		} catch (FileNotFoundException fe) {
			logger.error(fe);
		} catch (IOException ioe) {
			logger.error(ioe);
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException ex) {
				logger.error(ex);
			}
		}
		return content.toString();
	}

	public void analyzeCSVFile(String file) {
		InputStreamReader fr = null;
		BufferedReader br = null;
		try {
			fr = new InputStreamReader(new FileInputStream(file));
			br = new BufferedReader(fr);
			String rec = null;
			String[] argsArr = null;
			while ((rec = br.readLine()) != null) {
				System.out.println(rec);
				argsArr = rec.split(",");
				for (int i = 0; i < argsArr.length; i++) {
					System.out.println("seq " + (i + 1) + ":" + argsArr[i]);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fr != null)
					fr.close();
				if (br != null)
					br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	public synchronized static void logUploadedFileName(String logContent,
			String uploadLog, boolean append, String msg) throws IOException {
		FileWriter fw = null;
		try {
			logger.info(msg);
			fw = new FileWriter(uploadLog, append);	
			if(logContent!=null){ 
				if(!logContent.endsWith("\r\n")){
					logContent+="\r\n";
				}
				fw.write(logContent);
			}				
		} finally {
			try {
				if (fw != null)
					fw.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
	
	public synchronized static void delUploadedFileName(String csv,
			String uploadLog) throws IOException {
		List<String> csvList = getFileNamesUploaded(uploadLog);
		csvList.remove(csv);
		StringBuffer buf = new StringBuffer();
		for(String csvname : csvList){
			buf.append(csvname).append("\r\n");			
		}
		if(buf.length()>0)
			logUploadedFileName(buf.toString(),uploadLog,true,"because of download successfully, so delete csv file [" + csv + "] from UploadLog File [" + uploadLog+"]");
	} 

	public static void logDbErr(DownloadPayBean downloadPayBean,
			String dbErrLog, boolean append, String msg) {
		String logContent = "Date:" + PayUtil.getCurrDate() + "   AutoId:"
				+ downloadPayBean.getAutoId() + "   Alipay return status:"
				+ downloadPayBean.getStatus() + "   Database return result:"
				+ downloadPayBean.getRetstr();
		try {
			logUploadedFileName(logContent, dbErrLog, true, msg);
		} catch (Exception ex) {
			logger.info("when log database return result [" + logContent
					+ "], error occurs,please check it!");
			logger.error(ex);
		}
	}

	public static String getFileNameUploaded(String uploadLog)
			throws IOException {
		String cvsfilename = null;
		BufferedReader br = null;
		StringBuffer buf = new StringBuffer();
		try {
			br = new BufferedReader(new FileReader(uploadLog));
			cvsfilename = br.readLine();// 读取首行,然后从文件里删除该行
			if (cvsfilename != null && cvsfilename.trim().length() > 0
					&& !cvsfilename.equals("\r\n")) {
				String cvs;
				while ((cvs = br.readLine()) != null) {
					buf.append(cvs).append("\r\n");
				}
				logUploadedFileName(buf.toString(), uploadLog, false,
						"pop cvs-file-name [" + cvsfilename
								+ "] being download from " + uploadLog);
			} else {
				cvsfilename = null;
			}
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return cvsfilename;
	}
	
	public static List getFileNamesUploaded(String uploadLog)
			throws IOException {
		List csvList = new ArrayList();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(uploadLog));
			String cvs;
			StringBuffer buf = new StringBuffer();
			while ((cvs = br.readLine()) != null) {
				if (cvs.trim().length() > 0 && !cvs.equals("\r\n")) {
					csvList.add(cvs);
					buf.append(cvs).append(",");
				}
			}
			if (buf.length() > 0)
				logUploadedFileName("", uploadLog, false, "being ready for analyzing download zip file and remove all " + buf.toString() + " from "
						+ uploadLog);

		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return csvList;
	}

	public static void main(String[] args) {
		try {
			FileCSVHelper csvCre = new FileCSVHelper();
			csvCre.initGenerateCSVFile("e:\\test.csv");
			csvCre.setConvertFlag(true);
			csvCre.setData("aaa");
			csvCre.setData("aa,a");
			csvCre.writeLine();
			csvCre.setData("aa\"a");
			csvCre.setData("aa,a");
			csvCre.setData("aa,a");
			csvCre.writeLine();
			csvCre.setData("aa\"a");
			csvCre.setData("aa,\"a");
			csvCre.setData("aa,\"a");
			csvCre.setData("aa,\"a");
			csvCre.setData("aa,\"a");
			csvCre.writeLine();
			csvCre.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			FileCSVHelper csvAna = new FileCSVHelper();
			csvAna.setConvertFlag(true);
			/*
			 * ArrayList al = csvAna.analysisLine(); for (int i = 0; i <
			 * al.size(); i++) { ArrayList al1 = (ArrayList) al.get(i); for (int
			 * j = 0; j < al1.size(); j++) { System.out.println(al1.get(j)); } }
			 */
			csvAna.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?