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 <T> List<T> read(InputStream in, LineHandler lineHandler) {
		List<T> ts = new ArrayList<T>();
		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 <T> void read(InputStream in, LineHandler lineHandler,
			Consumer<List<T>> consumer, int threshold) {
		List<T> ts = new ArrayList<T>();
		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 <T> void read(String filePath, LineHandler lineHandler, Consumer<List<T>> 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 <T> void read(InputStream in, LineHandler lineHandler, Consumer<List<T>> consumer,
            int threshold, int ignoreLineCount) {
		List<T> ts = new ArrayList<T>();
		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<String> headerList, List<List<Object>> 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<Object> 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> 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;
	}
	
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值