我希望系统读取csv文件,以便分析csv文件的头和行。csv文件的头应该与ProductDetail.java的变量匹配。如果标头与这些变量匹配,则将读入数据库的行插入到这些标头下。
ProductDetail.java
public class ProductDetail {
String street;
String city;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
} ReadFile.java
public class ReadFile {
public static void main(String[] args) {
FileReader input = null;
BufferedReader br = null;
try {
input = new FileReader("uploadedFile.csv");
br = new BufferedReader(input);
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
input.close();
br.close();
}
catch (IOException x) {
x.printStackTrace();
}
}
}
}我已经启动了这个项目,但是现在我很难理解如何读取列和行,以及如何与在ProductDetail.java中设置的预定义的标头匹配。如果你能在这件事上帮我,那就太好了。
发布于 2016-10-23 17:58:18
使用SuperCSV,您可以这样做,以验证csv的头与预期的标头匹配。通常,预期的标头是固定的。所以,你应该把它们写成常量。
public static void main(String[] args) throws IOException {
CsvBeanReader csvBeanReader = null;
try {
// your csv file
String csvFile = null;
csvBeanReader = new CsvBeanReader(csvFile), CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE);
final String[] headersArray = csvBeanReader.getHeader(true);
List<String> headers = Arrays.asList(headersArray);
List<String> expectedHeaders = Arrays.asList("street", "city");
if (!expectedHeaders.equals(headers)) {
return;
}
final CellProcessor[] processors = new CellProcessor[] { new NotNull(), new NotNull() };
List<ProductDetail> productDetails = new ArrayList<>();
ProductDetail productDetail = null;
while ((productDetail = csvBeanReader.read(ProductDetail.class, headersArray, processors)) != null) {
productDetails.add(productDetail);
}
// save products in your DB
}
finally {
try {
csvBeanReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}发布于 2016-10-23 17:15:18
阅读CSV链接。CSV是逗号分隔的文件,如果您读取CSV,并使用逗号作为分隔符,并将CSV的第一行(如果将来的列顺序更改使用字符串比较)与数据库列名进行映射,那么您就完成了。
https://stackoverflow.com/questions/40205409
复制相似问题