Combine Columns in CSV file using JAVA

社会主义新天地 提交于 2019-12-13 09:06:45

问题


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".

This is My CSV File

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

Here is My Code

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

回答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();
}

this breaks the output only after ove SV line is writen




回答2:


Replace this: System.out.println(row[i]); With: System.out.print(row[i]+" ");

And as Dr. Y mentioned, add System.out.println(); after for loop

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();
}

Useful links for you:

Difference between print and println in java

How does System.out.ptintln() work ?



来源:https://stackoverflow.com/questions/30189108/combine-columns-in-csv-file-using-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!