使用JAVA在CSV文件中合并列 [英] Combine Columns in CSV file using JAVA

查看:1792
本文介绍了使用JAVA在CSV文件中合并列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Java合并csv文件中的列 在此文件中,我要合并前两列产品编号"和产品名称".

I want to combine columns in csv file using java here in this file i want combine first two columns "Product No" and "Product Name".

这是我的CSV文件

 Productno,Productname,Price,Quantity
 1,java,300,5
 2,java2,500,10
 3,java3,1100,120

这是我的代码

private void parseUsingOpenCSV(String filename) 

{
   CSVReader reader;
   FileWriter out = null;
   CSVWriter outt;
   try 
  {
  reader = new CSVReader(new FileReader(filename));
  String[] row;

   try {
    out= new FileWriter("E:/data/test/newww.csv");
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

   try {
    while ((row = reader.readNext()) != null) 
    {
        for (int i = 0; i < row.length; i++) 
        {
            // display CSV values


            System.out.println(row[i]);
            String com = row[i];

            out.write(com); 
        }

    }
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
} 
catch (FileNotFoundException e) 
{
    System.err.println(e.getMessage());
}finally{
  if (out != null) {
      try {
        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
   }
}   
}

通过使用此代码,我得到的输出如下

By using this code i get output is below

Product No
Product Name
Price
1
java
300
2
java2
500
3
java3
1100

但是我想要这样的输出....

But I want Output like this....

 ProductnoProductname,Price,Quantity
 1java,300,5
 2java2,500,10
 3java3,1100,120

推荐答案

while ((row = reader.readNext()) != null) 
{
    for (int i = 0; i < row.length; i++) 
    {
        // display CSV values


        System.out.print(row[i]);
        String com = row[i];

        out.write(com); 
    }
 System.out.println();
}

这仅在写入ove SV行之后才中断输出

this breaks the output only after ove SV line is writen

这篇关于使用JAVA在CSV文件中合并列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆