2016-11-15 2 views
0

2 개의 CSV 파일 (old.csv, change.csv)을 비교하는 방법과 다른 작업을 수행 한 후에 (추가, 업데이트, 삭제) new.csv 파일이 생성됩니다. 이 작업을 수행하는 방법에 대한 아이디어가 필요합니다. 필자는 FileReader와 Writer를 사용하여 파일을 읽고 쓸 수있었습니다. 파일을 비교하고 작업을 수행하는 방법을 모르겠습니다. 데이터 항목에 배열을 사용해야합니다.2 csv 파일을 비교하고 작업을 수행하고 새 CSV 파일로 출력

Old.csv 
CODE NAME ADDRESS NUMBER 
0001 John USA  1234 

Change.csv 
CHANGE CODE NAME ADDRESS NUMBER 
ADD  0002 Shane Germany 5678 
UPDATE 0001   Canada 

New.csv 
CODE NAME ADDRESS NUMBER 
0001 John Canada 1234 
0002 Shane Germany 5678 

아이디어를 도와주세요 :

내 CSV 파일은 열이 포함되어 있습니다. 미리 감사드립니다.

+0

파일 구조를 직접 결정할 수 있습니까? 그렇다면 ID를 추가하여 데이터 집합을 식별 할 것을 제안합니다. 그렇지 않으면 동일한 이름을 가진 즉시 문제가 발생합니다. 아니면 숫자 열이 의도 한 것입니까? csv를 MySQL 데이터베이스로 가져 오는 것을 고려 했습니까? 이 방법으로 SQL-Language를 사용하여 데이터 항목을 변경할 수 있습니다. – Gildraths

+0

기본 키는 CODENUMBER입니다. 죄송합니다. 추가하지 않았습니다. 나는 대신 데이터 엔트리를 위해 SQL 배열을 사용해야한다. – exceptione

답변

0

.

이 같은 모습 클래스 만들기 :

public class Person { 

    private String code; 
    private String name; 
    private String address; 
    private String number; 

    public Person(String code, String name, String address, String number) { 
     this.code = code; 
     this.name = name; 
     this.address = address; 
     this.number = number;    
    } 

    public String geCode() { 
     return code; 
    } 

    public void setCode(String code) { 
     this.code = code; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public String getAddress() { 
     return address; 
    } 

    public void setAddress(String address) { 
     this.address = address; 
    } 

    public String getNumber() { 
     return number; 
    } 

    public void setNumber(String number) { 
     this.number = number; 
    } 
} 

을하고 두 파일을 비교하는 응용 프로그램에서 데이터 홀더와 같은 클래스 이상 사용하고 새로 만들기를 아래

는 opencsv 사용 예입니다 CSV 파일

import com.opencsv.CSVReader; 
import com.opencsv.CSVWriter; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.util.HashMap; 
import java.util.Map; 
import java.util.TreeMap; 

public class NewClass1 { 
    public static void main(String[] args) { 
     try { 
      String oldFile = "Old.csv"; 
      String changeFile = "Change.csv"; 
      String newFile = "New.csv"; 
      Map<String,Person> personsList = readOldCsv(oldFile); 
      personsList = getChangesfromChangeCsv(changeFile,personsList); 
      writeNewCsvFile(newFile,personsList); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 
    //read your old csv file line by line and create an object person 
    //and put it in a map with code as key and person itself as value 
    //here assumed that your files are tab separeted '\t'; 
    //if not change to ';' or ',' according to your separator 
    public static Map<String,Person> readOldCsv(String fileName) throws IOException{ 
     Map<String,Person> personsList = new HashMap<>(); 
     String [] nextLine; 
     CSVReader reader = new CSVReader(new FileReader(fileName), '\t' ,'\'', 1); 
     while ((nextLine = reader.readNext()) != null) {   
      personsList.put(nextLine[0],new Person(nextLine[0], nextLine[1], nextLine[2], nextLine[3])); 
     }  
     return personsList;   
    } 
    // read your change csv file and add or update persons depending on the change column 
    public static Map<String,Person> getChangesfromChangeCsv(String fileName, Map<String,Person> personsList) throws IOException{    
     String [] nextLine; 
     CSVReader reader = new CSVReader(new FileReader(fileName), '\t' ,'\'', 1); 
     while ((nextLine = reader.readNext()) != null) { 
      switch(nextLine[0].toLowerCase()){ 
       case "add": 
        personsList.put(nextLine[1],new Person(nextLine[1], nextLine[2], nextLine[3], nextLine[4])); 
       case "update": 
        personsList.get(nextLine[1]).setName(!nextLine[2].isEmpty()? nextLine[2]:personsList.get(nextLine[1]).getName()); 
        personsList.get(nextLine[1]).setAddress(!nextLine[3].isEmpty()? nextLine[3]:personsList.get(nextLine[1]).getAddress()); 
        personsList.get(nextLine[1]).setNumber(!nextLine[4].isEmpty()? nextLine[4]:personsList.get(nextLine[1]).getNumber()); 
       default: 
        System.out.println("unexpected entry"); 
      }     
     } 
     // use TreeMap to get a map sorted by key 
     return new TreeMap<>(personsList);   
    } 

    //write the values of the map into a new csv file 
    private static void writeNewCsvFile(String filename,Map<String,Person> personsList) throws IOException {    
     CSVWriter writer = new CSVWriter(new FileWriter(filename,false), '\t',CSVWriter.NO_QUOTE_CHARACTER); 
     for(Person p : personsList.values()){ 
      String[] entries = {p.geCode(),p.getName(),p.getAddress(),p.getNumber()}; 
      writer.writeNext(entries); 
     }     
     writer.close();      
    } 
} 
+0

좋아! 나는 이것을 사용할 것이다. 고마워요! 나는 마침내 계몽한다 : D – exceptione

0

이름 열이 2 개의 CSV 파일 사이의 기본 키인 것처럼 보입니다. CSV 파일을 읽는 동안 유형의 해시 맵을 만들 수 있습니다. 여기서 Name = Name coulmn value이고 Data는 전체 개체입니다. 나중에 각 CSV 레코드 변경을 추적하면서 변경 사항을 처리하기 위해 switch 문을 사용할 수 있으며 각 경우마다 hashmap에 대한 개별 업데이트를 관리 할 수 ​​있습니다. 성공적인 탐색 후 해시 맵에는 필요한 업데이트 된 인스턴스가 포함되어 있으므로 새 csv로 이동하고 숨길 수 있습니다. 내가 opencsv 또는

supercsv 같은 CSV 파서를 사용하고 데이터 클래스의 사용을하는 것이 좋습니다 이러한 작업에 대한

관련 문제