2011-12-17 89 views
-1

我有两个csv文件,包含多个表中的多个列。我使用opencsv生成csv文件。 我想制作一个包含两个文件中所有列的csv文件。 这两个文件中都有一个共同的列。 但记录数量不相同。 请提出建议。任何帮助,将不胜感激。在java中将两个csv文件合并为一个

P.S .:连接两个文件只是意味着我想添加一个文件中的所有列..这不是数据库连接。 我想要组合的csv文件,并将其用于某些工具中以生成pdf

+0

如果它们不具有相同的列和不同的线数,* *你将如何合并它们?这里的逻辑是什么?输出文件是什么? –

+0

*“请提出建议。”*听起来不像是适合CSV的数据。找到另一个存储结构。 –

+0

我只想在一个CSV文件中的所有列,并进一步使用这个CSV文件..这是我面临的挑战,因为表是不相关的 – Shaireen

回答

3

将一个文件加载到由公用列值键入的字典中,然后将第二个文件的所有记录附加到字典(再次按公共列值)。
最后,将所有字典k,v对写入一个新文件。

即兴例如:

CSVReader r1 = ...; // reader of 1st file 
CSVReader r2 = ...; // reader of 2nd file 

HashMap<String,String[]> dic = new HashMap<String,String[]>(); 

int commonCol = 1; // index of the commonColumn 

r1.readNext(); // skip header 
String[] line = null; 
while ((line = r1.readNext()) != null) 
{ 
    dic.add(line[commonCol],line) 
} 

commonCol = 2; // index of the commonColumn in the 2nd file 

r2.readNext(); // skip header 
String[] line = null; 
while ((line = r2.readNext()) != null) 
{ 
    if (dic.keySet().contains(line[commonCol]) 
    { 
    // append line to existing entry 
    } 
    else 
    { 
    // create a new entry and pre-pend it with default values 
    // for the columns of file1 
    } 
} 

foreach (String[] line : dic.valueSet()) 
{ 
    // write line to the output file. 
} 
+0

你可以提供一些相同的代码片段..? – Shaireen

+0

我已经添加了一个基本的不完整(!)示例,它应该如何显示,并尝试调整它。 – yurib

0

我们可以做这样的事情,如果我们知道哪些列具有重复数据

int n1,n2;//stores the serial number of the column that has the duplicate data 
    BufferedReader br1=new BufferedReader(new InputStreamReader(new FileInputStream(f1))); 
    BufferedReader br2=new BufferedReader(new InputStreamReader(new FileInputStream(f2))); 
    String line1,line2; 
    while((line1=br1.readLine())!=null && (line2=br2.readLine())!=null){ 
     String line=line1+","+line2; 
     String newL=""; 
     StringTokenizer st=new StringTokenizer(line,","); 
     for(int i=1;i<=st.countTokens();i++){ 
      if((i==n1)||(i==n1+n2)) 
       continue; 
      else 
       newL=newL+","+st.nextToken(); 
     } 
     String l=newL.substring(1); 
     //write this line to the output file 
    } 
相关问题