Super CSV是個操作csv檔案的Open Source
由於我需要的是讀取csv檔案資料
所以
Code example也只先看這一部份了
實作上可以分做兩種情況
已知檔案格式和未知檔案格式
在已知的情況下
就它的範例
File Header的部份為以下
username, password, date, zip, town
Klaus, qwexyKiks, 17/1/2007, 1111, New York
Oufu, bobilop, 10/10/2007, 4555, New York
便可以做出對應的bean
public class UserBean {
String username, password, street, town;
int zip;
public String getPassword() { return password; }
public String getStreet() { return street; }
public String getTown() { return town; }
public String getUsername() { return username; }
public int getZip() { return zip; }
public void setPassword(String password) { this.password = password; }
public void setStreet(String street) { this.street = street; }
public void setTown(String town) { this.town = town; }
public void setUsername(String username) { this.username = username; }
public void setZip(int zip) { this.zip = zip; }
}
再來
可以透過processor做Header各欄位的格式檢查
final CellProcessor[] processors = new CellProcessor[] {
new Unique(new StrMinMax(5, 20)),
new StrMinMax(8, 35),
new ParseDate("dd/MM/yyyy"),
new Optional(new ParseInt()),
null
};
最後就是讀取的部份
class ReadingObjects {
public static void main(String[] args) throws Exception{
ICsvBeanReader inFile = new CsvBeanReader(new FileReader("foo.csv"), CsvPreference.EXCEL_PREFERENCE);
try {
final String[] header = inFile.getCSVHeader(true);
UserBean user;
while( (user = inFile.read(UserBean.class, header, processors)) != null) {
System.out.println(user.getZip());
}
} finally {
inFile.close();
}
}
}
雖然沒實際去測試
如果header的字眼有空白,特殊符號之類
這樣bean的方法是不是就不能用了?
第二類是未知格式
這部份在官網只寫了
You accomplish this using the CsvListReader.read() method
果然也是很簡單
我把方法寫在一起
可以做個對照
public static void main(String[] args) throws Exception {
ICsvBeanReader inFile = new CsvBeanReader(new FileReader("foo.csv"), CsvPreference.EXCEL_PREFERENCE);
CsvListReader r = new CsvListReader(new FileReader("foo.csv"), CsvPreference.EXCEL_PREFERENCE);
try {
final String[] header = inFile.getCSVHeader(true);
for(int j=0;j<header.length;j++){
System.out.println(header[j]);
}
UserBean user;
while( (user = inFile.read(UserBean.class, header, userProcessors)) != null) {
System.out.println(user.getZip());
}
List l;
while( (l = r.read()) !=null ){
System.out.println(l.get(0));
}
} finally {
inFile.close();
}
}