현재 여러 개의 CSV 파일을 읽어서 하나의 빈으로 파싱하기 전에 beanReader를 사용하여 여러 개의 CSV 파일을 읽으려고합니다.SuperCSV에서 여러 파일을 읽고 하나의 빈 객체로 구문 분석
지금까지 다른 파일의 열을 하나의 bean 객체로 구문 분석 할 수없는 것 같습니다. ICsvBeanReader로도 가능합니까?
현재 여러 개의 CSV 파일을 읽어서 하나의 빈으로 파싱하기 전에 beanReader를 사용하여 여러 개의 CSV 파일을 읽으려고합니다.SuperCSV에서 여러 파일을 읽고 하나의 빈 객체로 구문 분석
지금까지 다른 파일의 열을 하나의 bean 객체로 구문 분석 할 수없는 것 같습니다. ICsvBeanReader로도 가능합니까?
예, 가능합니다. 수퍼 CSV 2.2.0 현재 기존 콩을 읽을 수 있습니다 (javadoc 참조).
다음 예제에서는 3 개의 판독기를 동시에 사용합니다 (3 개의 다른 파일에서 작동). 첫 번째 판독기는 빈을 작성하는 데 사용되고 다른 2 개는 기존 빈을 갱신합니다. 이 방법은 각 파일의 행 수가 같고 각 행 번호가 동일한 사람을 나타내는 것으로 가정합니다. 일치하지 않으면 고유 식별자를 공유하지만 첫 번째 파일의 모든 레코드를 먼저 메모리로 읽은 다음 식별자의 두 번째/세 번째 일치에서 업데이트해야합니다.
나는 그것을 약간 똑똑하게 만들려고 노력했기 때문에 이름 매핑을 하드 코딩 할 필요가 없다. 단지 그것이 모르는 헤더를 null로 만든다 (그래서 Super CSV는 그렇지 않다. 빈에없는 필드를 매핑하려고 시도합니다. 웹 사이트의 partial reading examples을 참조하십시오. 물론 이것은 파일에 헤더가있는 경우에만 작동합니다. 그렇지 않으면 적절한 위치에 null이있는 매핑 배열을 하드 코딩해야합니다.
사람 콩
public class Person {
private String firstName;
private String sex;
private String country;
// getters/setters
}
예제 코드
public class Example {
private static final String FILE1 = "firstName,lastName\nJohn,Smith\nSally,Jones";
private static final String FILE2 = "age,sex\n21,male\n24,female";
private static final String FILE3 = "city,country\nBrisbane,Australia\nBerlin,Germany";
private static final List<String> DESIRED_HEADERS = Arrays.asList("firstName", "sex", "country");
@Test
public void testMultipleFiles() throws Exception {
try (
ICsvBeanReader reader1 = new CsvBeanReader(new StringReader(FILE1), CsvPreference.STANDARD_PREFERENCE);
ICsvBeanReader reader2 = new CsvBeanReader(new StringReader(FILE2), CsvPreference.STANDARD_PREFERENCE);
ICsvBeanReader reader3 = new CsvBeanReader(new StringReader(FILE3), CsvPreference.STANDARD_PREFERENCE);){
String[] mapping1 = getNameMappingFromHeader(reader1);
String[] mapping2 = getNameMappingFromHeader(reader2);
String[] mapping3 = getNameMappingFromHeader(reader3);
Person person;
while((person = reader1.read(Person.class, mapping1)) != null){
reader2.read(person, mapping2);
reader3.read(person, mapping3);
System.out.println(person);
}
}
}
private String[] getNameMappingFromHeader(ICsvBeanReader reader) throws IOException{
String[] header = reader.getHeader(true);
// only read in the desired fields (set unknown headers to null to ignore)
for (int i = 0; i < header.length; i++){
if (!DESIRED_HEADERS.contains(header[i])){
header[i] = null;
}
}
return header;
}
}
출력
Person [firstName=John, sex=male, country=Australia]
Person [firstName=Sally, sex=female, country=Germany]
감사합니다 많이! 대접처럼 일했다 :) – joey7492