我需要找到一种方法,根据输入的csv文件中特定列的值将csv文件拆分为多个csv文件。我还需要新生成的csv文件的名称作为该列的值。
For example:
input CSV file =
Col1,Col2,Col3
1,2,Cat
1,3,Cat
2,4,Dog
2,5,Dog
I want to split by Col3 so I get the following table and file name:
---------------- File name = Cat.csv
Col1,Col2,Col3
1,2,Cat
1,3,Cat
---------------- File name = Dog.csv
Col1,Col2,Col3
2,4,Dog
2,5,Dog
有什么办法吗?
感谢您的帮助。
到目前为止,我只能读取文件并保存在对象中。
package com.jcg;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CsvFileReader {
private static final String COMMA_DELIMITER = ",";
private static final int ORDER_ID_IDX = 0;
private static final int ORDER_DATE_IDX = 1;
private static final int ORDER_COUNTRY_IDX = 2;
private static final int ORDER_VALUE = 3;
public static void readCsvFile(String fileName) {
BufferedReader fileReader = null;
try {
List<Order> orders = new ArrayList<Order>();
String line = "";
fileReader = new BufferedReader(new FileReader(fileName));
fileReader.readLine();
while ((line = fileReader.readLine()) != null) {
String[] tokens = line.split(COMMA_DELIMITER);
if (tokens.length > 0) {
Order order = new Order(Long.parseLong(tokens[ORDER_ID_IDX]), tokens[ORDER_DATE_IDX],
tokens[ORDER_COUNTRY_IDX], tokens[ORDER_VALUE]);
orders.add(order);
}
}
for (Order order : orders) {
System.out.println(order.toString());
}
} catch (Exception e) {
System.out.println("Error in CsvFileReader !!!");
e.printStackTrace();
} finally {
try {
fileReader.close();
} catch (IOException e) {
System.out.println("Error while closing fileReader !!!");
e.printStackTrace();
}
}
}
}
Order.java
package com.jcg;
public class Order {
private long id;
private String dates;
private String country;
private String values;
public Order(long id, String dates, String country, String values) {
super();
this.id = id;
this.dates = dates;
this.country = country;
this.values = values;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getDates() {
return dates;
}
public void setDates(String dates) {
this.dates = dates;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getValues() {
return values;
}
public void setValues(String values) {
this.values = values;
}
@Override
public String toString() {
return "Order [id=" + id + ", dates=" + dates + ", country=" + country + ", values=" + values + "]";
}
}