Java学习笔记-CSV文件的读写操作

CSV文件读写简单示例:

import org.platform.utils.file.FileCharsetUtils;
import org.platform.utils.file.LineHandler;
import org.platform.utils.file.PathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

public class CsvFileUtils {
	
	private static Logger LOG = LoggerFactory.getLogger(CsvFileUtils.class);
	
	public static  List read(InputStream in, LineHandler lineHandler) {
		List ts = new ArrayList();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(in));
			String line = null;
			while ((line = br.readLine()) != null) {
				ts.add(lineHandler.handle(line));
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		} finally {
			try {
				if (null != in) in.close();
				if (null != br) br.close();
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
			}
		}
		return ts;
	}
	
	public static  void read(InputStream in, LineHandler lineHandler,
			Consumer> consumer, int threshold) {
		List ts = new ArrayList();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(in));
			String line = null;
			while ((line = br.readLine()) != null) {
				ts.add(lineHandler.handle(line));
				if (ts.size() > threshold) {
					consumer.accept(ts);
					ts.clear();
				}
			}
			if (ts.size() > 0) {
				consumer.accept(ts);
				ts.clear();
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		} finally {
			try {
				if (null != in) in.close();
				if (null != br) br.close();
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
			}
		}
	}
	
	public static  void read(String filePath, LineHandler lineHandler, Consumer> consumer,
            int threshold, int ignoreLineCount) {
		try {
			read(new FileInputStream(new File(filePath)), lineHandler, consumer, threshold, ignoreLineCount);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
	}
	
	public static  void read(InputStream in, LineHandler lineHandler, Consumer> consumer,
            int threshold, int ignoreLineCount) {
		List ts = new ArrayList();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(in));
			for (int i = 0; i < ignoreLineCount; i++) 
				br.readLine();
			String line = null;
			while ((line = br.readLine()) != null) {
				ts.add(lineHandler.handle(line));
				if (ts.size() > threshold) {
					consumer.accept(ts);
					ts.clear();
				}
			}
			if (ts.size() > 0) {
				consumer.accept(ts);
				ts.clear();
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		} finally {
			try {
				if (null != in) in.close();
				if (null != br) br.close();
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
			}
		}
	}

	public static final String OS_NAME = System.getProperty("os.name").toLowerCase().trim();

	public static void write(List headerList, List> resultList, OutputStream outputStream) {
		File file = null;
		BufferedWriter bufferedWriter = null;
		try {
			String directory = OS_NAME.indexOf("windows") != - 1 ? System.getProperty("java.io.tmpdir") :
				PathUtils.getJarFileMultiParentPath(1, "commonfiles");
			file = new File(directory + Calendar.getInstance().getTimeInMillis() + ".csv");
			if (file.exists()) file.delete();
			file.createNewFile();
			// 文件乱码处理
			String charset = OS_NAME.indexOf("windows") != - 1 ? "GBK" : "UTF-8";
			bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset), 1024);
			// 写入前段字节流,防止乱码
			//bufferedWriter.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }));
			// HEADER
			bufferedWriter.write(headerList.stream().collect(Collectors.joining(",")));
			bufferedWriter.newLine();
			// CONTENT
			for (int i = 0, len = resultList.size(); i < len; i++) {
				List result = resultList.get(i);
				bufferedWriter.write(result.stream().map(v -> null == v ? "" : String.valueOf(v)).collect(Collectors.joining(",")));
				bufferedWriter.newLine();
			}
			bufferedWriter.flush();
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		} finally {
			try {
				if (null != bufferedWriter) bufferedWriter.close();
			} catch (IOException e) {
				LOG.error(e.getMessage(), e);
			}
		}
		InputStream in = null;
		try {
			in = new FileInputStream(file);
			int len = 0;
			byte[] buffer = new byte[1024];
			while ((len = in.read(buffer)) > 0) {
				outputStream.write(buffer, 0, len);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		} finally {
			try {
				if (null != in) in.close();
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
			}
		}
		if (file.exists()) file.delete();
	}

}
public abstract class LineHandler {

	/**
	 * 处理行数据
	 * @param line
	 * @return
	 */
	public abstract  T handle(String line);
	
	/**
	 * 过滤行数据
	 * @param line
	 * @return
	 */
	public boolean filter(String line) {return false;}
	
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URLDecoder;

public class PathUtils {
	
	private static Logger LOG = LoggerFactory.getLogger(PathUtils.class);
	
	private static String codeSourcePath = null;
	
	static {
		codeSourcePath = org.platform.utils.web.PathUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		try {
			codeSourcePath = URLDecoder.decode(codeSourcePath, "UTF-8");
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
	}
	
	public static String getJarFileParentPath() {
		if (codeSourcePath.endsWith(".jar"))
			return codeSourcePath.substring(0, codeSourcePath.lastIndexOf("/") + 1);
		return codeSourcePath;
	}
	
	public static String getJarFileMultiParentPath(int level, String dirName) {
		String parentPath = getJarFileParentPath();
		for (int i = 0; i < level; i++) {
			parentPath = parentPath + ".." + File.separator;
		}
		parentPath = parentPath + dirName;
		File destFile = new File(parentPath);
		if (!destFile.exists()) destFile.mkdirs();
		return parentPath;
	}
	
}

 

你可能感兴趣的:(J2EE,Java,CSV)