首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将文件的内容(头)与java中定义的变量和数据库中的更新进行比较?

如何将文件的内容(头)与java中定义的变量和数据库中的更新进行比较?
EN

Stack Overflow用户
提问于 2016-10-23 16:56:43
回答 2查看 1.6K关注 0票数 0

我希望系统读取csv文件,以便分析csv文件的头和行。csv文件的头应该与ProductDetail.java的变量匹配。如果标头与这些变量匹配,则将读入数据库的行插入到这些标头下。

ProductDetail.java

代码语言:javascript
复制
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

代码语言:javascript
复制
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中设置的预定义的标头匹配。如果你能在这件事上帮我,那就太好了。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-10-23 17:58:18

使用SuperCSV,您可以这样做,以验证csv的头与预期的标头匹配。通常,预期的标头是固定的。所以,你应该把它们写成常量。

代码语言:javascript
复制
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();
    }
}
}
票数 0
EN

Stack Overflow用户

发布于 2016-10-23 17:15:18

阅读CSV链接。CSV是逗号分隔的文件,如果您读取CSV,并使用逗号作为分隔符,并将CSV的第一行(如果将来的列顺序更改使用字符串比较)与数据库列名进行映射,那么您就完成了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40205409

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档