欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-26 17:10:14
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;im...

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;
	}
	
}

 

本文地址:https://blog.csdn.net/wulinshishen/article/details/110293758

相关标签: J2EE Java CSV