使用JAVA

时间:2015-05-12 11:10:28

标签: java csv edit

我想使用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

2 个答案:

答案 0 :(得分: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();
}

只有在写入超出SV行后才会中断输出

答案 1 :(得分:0)

替换为: System.out.println(row[i]); 使用: System.out.print(row[i]+" ");

博士一样。提及,在System.out.println();

之后添加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();
}

有用的链接:

Difference between print and println in java

How does System.out.ptintln() work ?