【问题标题】:Combine Columns in CSV file using JAVA使用 JAVA 合并 CSV 文件中的列
【发布时间】:2024-01-01 05:41:01
【问题描述】:

我想使用 java 合并 csv 文件中的列 在这个文件中,我想结合前两列“产品编号”和“产品名称”。

这是我的 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();
    }
   }
}   
}

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

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

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

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

【问题讨论】:

  • 尝试使用 print 代替 println
  • 使用打印我得到这样的输出“Product NoProduct NamePrice1java3002java25003java31100”
  • 我想合并列而不是所有数据
  • 正如你在下面的帖子中看到的,在每次迭代后添加一个 println

标签: java csv edit


【解决方案1】:
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 行被写入后才会中断输出

【讨论】:

  • 你应该很容易添加逗号。
  • 你能告诉我我能做什么吗?
  • 这真的是很基础的东西,看来你应该为初学者学习java。
【解决方案2】:

替换这个: System.out.println(row[i]); 与: System.out.print(row[i]+" ");

作为博士。 Y 提到,在for loop 之后添加System.out.println();

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


        System.out.print(row[i]+", "); // here is the commas 
        String com = row[i];

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

对您有用的链接:

Difference between print and println in java

How does System.out.ptintln() work ?

【讨论】:

  • 我也使用这个,但我得到这样的输出“Product NoProduct NamePrice1java3002java25003java31100”
  • 好吧 - System.out.print(row[i]+" ");