csv 파일 생성 샘플.
주로 public get 메소드의 값으로 csv 파일을 생성하기 위한 것.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/*
* Csv 파일 양식 파일을 생성한다.
*/
public class CsvWriter {
private String csvDelimeter = "\t";
private String lineSeparator = System.lineSeparator();
private String methodPrefix = "";
private Pattern patternCols = null;
@SuppressWarnings("rawtypes")
private Class writeClass = Object.class;
@SuppressWarnings("rawtypes")
public CsvWriter(Class clz, String csvDelimeter, String lineSeparator, String methodPrefix) {
this.writeClass = clz;
this.csvDelimeter = csvDelimeter;
this.lineSeparator = lineSeparator;
this.methodPrefix = methodPrefix;
}
@SuppressWarnings("rawtypes")
public CsvWriter(Class clz, String methodPrefix) {
this.writeClass = clz;
this.methodPrefix = methodPrefix;
}
@SuppressWarnings("rawtypes")
public CsvWriter(Class clz, String methodPrefix, String regexpIncludeCols) {
this.writeClass = clz;
this.methodPrefix = methodPrefix;
if(regexpIncludeCols != null) {
this.patternCols = Pattern.compile(regexpIncludeCols, Pattern.CASE_INSENSITIVE); // 대소문자 무시
}
}
/**
* Csv 파일 양식 파일을 생성한다.
* <pre>
* String filePath = "C:\\output.csv";
* List<Object> objectList = list.stream()
* .map(m -> (Object)m)
* .collect(Collectors.toList());
* String regexpColsName = "id|name";
* CsvWriter csv = new CsvWriter(클래스.class, "get", regexpColsName);
* csv.writeObjectToCsv(filePath, objectList);
* </pre>
* @param filePath
* @param list
*/
public void writeObjectToCsv(String filePath, List<Object> list) {
List<Method> methodlist = listgetMethod(writeClass);
StringBuilder sb = new StringBuilder(1000);
sb.append(getColNames(methodlist, csvDelimeter));
for(Object lot : list) {
sb.append(lineSeparator).append(getColValues(methodlist, lot, csvDelimeter));
}
// log.info(sb.toString());
writeCSV(filePath, sb.toString());
}
public String getColNames(List<Method> list, String csvDelimeter) {
StringBuilder sb = new StringBuilder(200);
for(int i = 0; i < list.size(); i++) {
if(i > 0)
sb.append(csvDelimeter);
sb.append(list.get(i).getName().substring(3)); // get 이후
}
return sb.toString();
}
public String getColValues(List<Method> list, Object obj, String csvDelimeter) {
StringBuilder sb = new StringBuilder(200);
String EMPTY = "";
for(int i = 0; i < list.size(); i++) {
if(i > 0)
sb.append(csvDelimeter);
try {
Object returnObj = list.get(i).invoke(obj);
if(returnObj != null)
sb.append(returnObj.toString());
else
sb.append(EMPTY);
} catch (Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}
@SuppressWarnings("rawtypes")
public List<Method> listgetMethod(Class clz) {
List<Method> list = new ArrayList<>();
for (Method method : clz.getMethods()) {
if(!Modifier.isPublic(method.getModifiers())) // public 아니면 skip
continue;
if(methodPrefix != null && methodPrefix.length() > 0 && !method.getName().startsWith(methodPrefix)) // prefix와 같지 않으면 skip
continue;
if(patternCols != null) {
String colName = methodPrefix == null? method.getName() : method.getName().substring(methodPrefix.length());
if(!this.patternCols.matcher(colName).find()) // colume 목록와 매칭되지 않으면 skip
continue;
}
Class returnClass = method.getReturnType();
if(returnClass.isPrimitive() || method.getReturnType() == String.class || method.getReturnType() == Long.class || method.getReturnType() == Integer.class) {
list.add(method);
}
}
list = list.stream().sorted(Comparator.comparing(Method::getName)).collect(Collectors.toList());
return list;
}
public void writeCSV(String filePath, String contents) {
BufferedWriter writer = null;
try {
int BUFFER_SIZE = 1024 * 20;
FileOutputStream out = new FileOutputStream(new File(filePath));
writer = new BufferedWriter(new OutputStreamWriter(out, "EUC-KR"), BUFFER_SIZE);
writer.write(contents);
} catch (IOException e) {
throw new IllegalStateException("Can't create writer ", e);
} finally {
try {
if(writer != null)
writer.close();
} catch (IOException e) {
}
}
}
}
728x90
'Programming Language > Java' 카테고리의 다른 글
cmd script - jar application 이 미실행 중일 때만, start 수행 (0) | 2024.11.11 |
---|---|
java application - start cmd / stop cmd (1) | 2024.11.09 |
logback 명에 따른 config 재설정 로직 (not Spring) (1) | 2024.11.07 |
G1 GC에서는 Full GC는 잘 안일어난다 (0) | 2023.08.05 |
Spring Webflux timout 설정 (0) | 2023.07.19 |