我想使用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
答案 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();
}
有用的链接: