我有两个csv文件,包含多个表中的多个列。我使用opencsv生成csv文件。 我想制作一个包含两个文件中所有列的csv文件。 这两个文件中都有一个共同的列。 但记录数量不相同。 请提出建议。任何帮助,将不胜感激。在java中将两个csv文件合并为一个
P.S .:连接两个文件只是意味着我想添加一个文件中的所有列..这不是数据库连接。 我想要组合的csv文件,并将其用于某些工具中以生成pdf
我有两个csv文件,包含多个表中的多个列。我使用opencsv生成csv文件。 我想制作一个包含两个文件中所有列的csv文件。 这两个文件中都有一个共同的列。 但记录数量不相同。 请提出建议。任何帮助,将不胜感激。在java中将两个csv文件合并为一个
P.S .:连接两个文件只是意味着我想添加一个文件中的所有列..这不是数据库连接。 我想要组合的csv文件,并将其用于某些工具中以生成pdf
将一个文件加载到由公用列值键入的字典中,然后将第二个文件的所有记录附加到字典(再次按公共列值)。
最后,将所有字典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.
}
我们可以做这样的事情,如果我们知道哪些列具有重复数据
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
}
如果它们不具有相同的列和不同的线数,* *你将如何合并它们?这里的逻辑是什么?输出文件是什么? –
*“请提出建议。”*听起来不像是适合CSV的数据。找到另一个存储结构。 –
我只想在一个CSV文件中的所有列,并进一步使用这个CSV文件..这是我面临的挑战,因为表是不相关的 – Shaireen