如何编写List< String>到csv文件&使用supercsv读回 [英] How to write List<String> to csv file & read it back using supercsv

查看:176
本文介绍了如何编写List< String>到csv文件&使用supercsv读回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用supercsv CsvBeanWriter将值写入csv文件。

Am using supercsv CsvBeanWriter to write values to csv file.

示例类:

public class Employee {
    private String name;

    private int empId;

    List<String> phoneNumbers;
}

我得到的输出是:

name,empId,phoneNumbers
vijay,1,"[123, 456]"

注意 List< String> phoneNumbers 写在 []

我的问题是如何读回到Employee类(bean)使用supercsv。

My Question is how do I read it back to Employee class(bean)using supercsv.

我尝试使用 CsvBeanReader & CsvDozerBeanReader ,但无法读取列表< String>

I tried using CsvBeanReader & CsvDozerBeanReader but not able to read the List<String>.

我收到非法报价例外。

Am getting illegalargument exception. Will be thankful for any pointers !

完成代码:

public class DozerBeanReader {
public static void main(String [] args){
    ICsvDozerBeanReader beanReader = null;

    try {
        beanReader = new CsvDozerBeanReader(new FileReader("Employee.csv"), 
                CsvPreference.STANDARD_PREFERENCE);

        String [] header = beanReader.getHeader(true); // ignore the header

        Class<?> [] hintTypes = {String.class, Integer.class, List.class};

        beanReader.configureBeanMapping(Employee.class, header, hintTypes);

        Employee readEmp1 = beanReader.read(Employee.class);
        readEmp1.toString();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}
}


推荐答案

您依赖于您的列表的电话号码被写为单个CSV列使用列表的 toString()格式,例如 [123,456]

You're relying on the fact that your List of phone numbers is written as a single CSV column using the List's toString()format, e.g. [123, 456].

您会收到类似以下的例外:

You will be getting an exception something like the following:

org.dozer.MappingException: Illegal object type 
for the method 'setPhoneNumbers'. 
Expected types: 
java.util.List
Actual types: 
java.lang.String

因为Dozer不知道如何将String [123,456] 转换为 List 。您可以执行此操作,但您需要撰写单元处理器将该字符串转换回 List 。如果你的电话号码纯粹是数字,不应该太难,但如果你的电话号码有逗号,那么事情会变得麻烦!

because Dozer has no idea how to convert the String [123, 456] to a List. You can do this, but you'll need to write a cell processor to convert that String back to a List. If your phone numbers are purely numbers that shouldn't be too hard, but if your phone numbers have commas then things are going to get messy!

我建议写每个电话号码作为一个单独的列 - 这使得它更容易(对于任何人阅读您的文件,包括你!)

I'd recommend writing each phone number as a separate column - it makes it so much easier (for anyone reading your file, including you!).

所有你需要做的是使用CsvDozerBeanReader和CsvDozerBeanWriter和索引映射

All you'll need to do is use CsvDozerBeanReader and CsvDozerBeanWriter with indexed mapping.

下面是一个例子 - 关键部分是索引映射:

Here's an example - the key part is the indexed mapping:

String[] fieldMapping = new String[] { "name",
    "empId", "phoneNumbers[0]", "phoneNumbers[1]" };




  • 我已定义了2个电话号码列 -

  • 我可以为标题使用fieldMapping,但选择使用更易读的自定义标题


  • 我使用StringReader / StringWriter只是为了简化示例

    • I've defined 2 phone number columns - if your List will have more, then just add more columns
    • I could have used the fieldMapping for the header, but chose to use a more readable custom header
    • You shouldn't need the hints as you've got in your question
    • I've used StringReader/StringWriter just to make the example simple
    • 示例:

      // create employee to write/read
      Employee employee = new Employee();
      employee.setEmpId(1234);
      employee.setName("Vijay");
      employee.setPhoneNumbers(Arrays.asList("123", "456"));
      
      // the CSV header
      String[] header = new String[] { "name",
          "empId", "phoneNumber1", "phoneNumber2" };
      
      // the field mapping
      String[] fieldMapping = new String[] { "name",
          "empId", "phoneNumbers[0]", "phoneNumbers[1]" };
      
      // write the employee
      StringWriter out = new StringWriter();
      ICsvDozerBeanWriter writer = 
          new CsvDozerBeanWriter(out,
          CsvPreference.STANDARD_PREFERENCE);
      writer.configureBeanMapping(Employee.class, fieldMapping);
      writer.writeHeader(header);
      writer.write(employee);
      writer.flush();
      
      // read the employee
      ICsvDozerBeanReader reader = 
          new CsvDozerBeanReader(new StringReader(out.toString()),
          CsvPreference.STANDARD_PREFERENCE);
      reader.configureBeanMapping(Employee.class, fieldMapping);
      reader.getHeader(true); // ignore header
      Employee e = reader.read(Employee.class);
      System.out.println(e);
      

      假设你写了 toString()方法,这应该打印

      Assuming you've written the toString() method, this should print

      Employee [name=Vijay, empId=1234, phoneNumbers=[123, 456]]
      

      这篇关于如何编写List&lt; String&gt;到csv文件&amp;使用supercsv读回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆