2010-09-08 31 views
16

Quiero escribir un objeto en el archivo CSV. Para XML tenemos XStream como this
Entonces, si quiero convertir objetos a CSV, ¿tenemos alguna de esas bibliotecas?¿Cómo serializar el objeto al archivo CSV?

EDIT: Quiero pasar mi lista de Bean a un método que debe escribir todos los campos de frijol en CSV.

Respuesta

19

En primer lugar, la serialización es escribir el objeto en un archivo 'tal como está'. AFAIK, no puedes elegir formatos de archivos y todo. El objeto serializado (en un archivo) tiene su propio 'formato de archivo'

Si desea escribir el contenido de un objeto (o una lista de objetos) en un archivo CSV, puede hacerlo usted mismo, no debería ser complejo.

Parece que Java CSV Library puede hacer esto, pero yo no lo he probado.

EDIT: Vea la muestra siguiente. Esto de ninguna manera es infalible, pero puedes construir sobre esto.

//European countries use ";" as 
    //CSV separator because "," is their digit separator 
    private static final String CSV_SEPARATOR = ","; 
    private static void writeToCSV(ArrayList<Product> productList) 
    { 
     try 
     { 
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("products.csv"), "UTF-8")); 
      for (Product product : productList) 
      { 
       StringBuffer oneLine = new StringBuffer(); 
       oneLine.append(product.getId() <=0 ? "" : product.getId()); 
       oneLine.append(CSV_SEPARATOR); 
       oneLine.append(product.getName().trim().length() == 0? "" : product.getName()); 
       oneLine.append(CSV_SEPARATOR); 
       oneLine.append(product.getCostPrice() < 0 ? "" : product.getCostPrice()); 
       oneLine.append(CSV_SEPARATOR); 
       oneLine.append(product.isVatApplicable() ? "Yes" : "No"); 
       bw.write(oneLine.toString()); 
       bw.newLine(); 
      } 
      bw.flush(); 
      bw.close(); 
     } 
     catch (UnsupportedEncodingException e) {} 
     catch (FileNotFoundException e){} 
     catch (IOException e){} 
    } 

Se trata de productos (captadores y definidores ocultos para facilitar la lectura):

class Product 
{ 
    private long id; 
    private String name; 
    private double costPrice; 
    private boolean vatApplicable; 
} 

Y así es como he comprobado:

public static void main(String[] args) 
{ 
    ArrayList<Product> productList = new ArrayList<Product>(); 
    productList.add(new Product(1, "Pen", 2.00, false)); 
    productList.add(new Product(2, "TV", 300, true)); 
    productList.add(new Product(3, "iPhone", 500, true)); 
    writeToCSV(productList); 
} 

Espero que esto ayude.

Saludos.

+0

1 escritura es muy simple, la lectura es un poco más difícil, pero no tanto ... y si no hay una nueva línea dentro de los valores de salida, la lectura se vuelve realmente simple ... – Vinze

+0

no cumple mis requisitos –

+1

@NewBie_Java: Si la Biblioteca CSV de Java no satisface sus requisitos, puede escribir su propia lógica. No es difícil, y no daña ... Han agregado una lógica simple sobre cómo hacer esto. Intente construir sobre eso ... – Nivas

4

Para facilitar el acceso CSV, hay una biblioteca llamada OpenCSV. Realmente facilita el acceso al contenido de archivos CSV.

EDITAR

De acuerdo con su actualización, considero que todas las respuestas anteriores como incorrecta (debido a su bajo nivelación). A continuación, puede ir de una manera completamente diferente, la forma de hibernación, de hecho!

Al usar el controlador CsvJdbc, puede cargar sus archivos CSV como fuente de datos JDBC, y luego asignar directamente sus beans a esta fuente de datos.

Hubiera hablado con usted acerca de CSVObjects, pero como el sitio parece estar roto, me temo que la lib no estará disponible hoy en día.

+0

OpenCSV no satisface mis requisitos –

+1

Tengo un requisito similar. De acuerdo con los documentos API, la versión 2.4 tiene una clase BeanToCsv. Desafortunadamente, parece que aún no se ha lanzado 2.4. – theblang

3

Sería interesante tener un serializador csv, ya que ocuparía el espacio mínimo en comparación con otros métodos de serialización.

El soporte más cercano a objeto java a CSV es StringUtils proporcionadas por proyecto resorte utils

arrayToCommaDelimitedString (Object [] arr) pero está lejos de ser un serializador.

Aquí es una sencilla utilidad que utiliza la reflexión para serializar valor objetos

public class CSVWriter 
{ 
private static String produceCsvData(Object[] data) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException 
{ 
    if(data.length==0) 
    { 
     return ""; 
    } 

    Class classType = data[0].getClass(); 
    StringBuilder builder = new StringBuilder(); 

    Method[] methods = classType.getDeclaredMethods(); 

    for(Method m : methods) 
    { 
     if(m.getParameterTypes().length==0) 
     { 
      if(m.getName().startsWith("get")) 
      { 
       builder.append(m.getName().substring(3)).append(','); 
      } 
      else if(m.getName().startsWith("is")) 
      { 
       builder.append(m.getName().substring(2)).append(','); 
      } 

     } 

    } 
    builder.deleteCharAt(builder.length()-1); 
    builder.append('\n'); 
    for(Object d : data) 
    { 
     for(Method m : methods) 
     { 
      if(m.getParameterTypes().length==0) 
      { 
       if(m.getName().startsWith("get") || m.getName().startsWith("is")) 
       { 
        System.out.println(m.invoke(d).toString()); 
        builder.append(m.invoke(d).toString()).append(','); 
       } 
      } 
     } 
     builder.append('\n'); 
    } 
    builder.deleteCharAt(builder.length()-1); 
    return builder.toString(); 
} 

public static boolean generateCSV(File csvFileName,Object[] data) 
{ 
    FileWriter fw = null; 
    try 
    { 
     fw = new FileWriter(csvFileName); 
     if(!csvFileName.exists()) 
      csvFileName.createNewFile(); 
     fw.write(produceCsvData(data)); 
     fw.flush(); 
    } 
    catch(Exception e) 
    { 
     System.out.println("Error while generating csv from data. Error message : " + e.getMessage()); 
     e.printStackTrace(); 
     return false; 
    } 
    finally 
    { 
     if(fw!=null) 
     { 
      try 
      { 
       fw.close(); 
      } 
      catch(Exception e) 
      { 
      } 
      fw=null; 
     } 
    } 
    return true; 
} 

}

Aquí es un objeto ejemplo valor

public class Product { 
private String name; 
private double price; 
private int identifier; 
private boolean isVatApplicable; 
public Product(String name, double price, int identifier, 
     boolean isVatApplicable) { 
    super(); 
    this.name = name; 
    this.price = price; 
    this.identifier = identifier; 
    this.isVatApplicable = isVatApplicable; 
} 
public String getName() { 
    return name; 
} 
public void setName(String name) { 
    this.name = name; 
} 
public double getPrice() { 
    return price; 
} 
public void setPrice(long price) { 
    this.price = price; 
} 
public int getIdentifier() { 
    return identifier; 
} 
public void setIdentifier(int identifier) { 
    this.identifier = identifier; 
} 
public boolean isVatApplicable() { 
    return isVatApplicable; 
} 
public void setVatApplicable(boolean isVatApplicable) { 
    this.isVatApplicable = isVatApplicable; 
} 

}

y el código para ejecutar el util

public class TestCSV 
{ 
public static void main(String... a) 
{ 
    Product[] list = new Product[5]; 
    list[0] = new Product("dvd", 24.99, 967, true); 
    list[1] = new Product("pen", 4.99, 162, false); 
    list[2] = new Product("ipad", 624.99, 234, true); 
    list[3] = new Product("crayons", 4.99,127, false); 
    list[4] = new Product("laptop", 1444.99, 997, true); 
    CSVWriter.generateCSV(new File("C:\\products.csv"),list); 
} 

} 

Salida:

Name VatApplicable Price Identifier 
dvd  true   24.99 967 
pen  false   4.99 162 
ipad true   624.99 234 
crayons false   4.99 127 
laptop true   1444.99 997 
+0

cómo leer el archivo del serializador CSV. –

0

escribí una clase simple que utiliza OpenCSV y tiene dos static public métodos.

static public File toCSVFile(Object object, String path, String name) { 
    File pathFile = new File(path); 
    pathFile.mkdirs(); 
    File returnFile = new File(path + name); 
    try { 

     CSVWriter writer = new CSVWriter(new FileWriter(returnFile)); 
     writer.writeNext(new String[]{"Member Name in Code", "Stored Value", "Type of Value"}); 
     for (Field field : object.getClass().getDeclaredFields()) { 
      writer.writeNext(new String[]{field.getName(), field.get(object).toString(), field.getType().getName()}); 
     } 
     writer.flush(); 
     writer.close(); 
     return returnFile; 
    } catch (IOException e) { 
     Log.e("EasyStorage", "Easy Storage toCSVFile failed.", e); 
     return null; 
    } catch (IllegalAccessException e) { 
     Log.e("EasyStorage", "Easy Storage toCSVFile failed.", e); 
     return null; 
    } 
} 

static public void fromCSVFile(Object object, File file) { 
    try { 
     CSVReader reader = new CSVReader(new FileReader(file)); 
     String[] nextLine = reader.readNext(); // Ignore the first line. 
     while ((nextLine = reader.readNext()) != null) { 
      if (nextLine.length >= 2) { 
       try { 
        Field field = object.getClass().getDeclaredField(nextLine[0]); 
        Class<?> rClass = field.getType(); 
        if (rClass == String.class) { 
         field.set(object, nextLine[1]); 
        } else if (rClass == int.class) { 
         field.set(object, Integer.parseInt(nextLine[1])); 
        } else if (rClass == boolean.class) { 
         field.set(object, Boolean.parseBoolean(nextLine[1])); 
        } else if (rClass == float.class) { 
         field.set(object, Float.parseFloat(nextLine[1])); 
        } else if (rClass == long.class) { 
         field.set(object, Long.parseLong(nextLine[1])); 
        } else if (rClass == short.class) { 
         field.set(object, Short.parseShort(nextLine[1])); 
        } else if (rClass == double.class) { 
         field.set(object, Double.parseDouble(nextLine[1])); 
        } else if (rClass == byte.class) { 
         field.set(object, Byte.parseByte(nextLine[1])); 
        } else if (rClass == char.class) { 
         field.set(object, nextLine[1].charAt(0)); 
        } else { 
         Log.e("EasyStorage", "Easy Storage doesn't yet support extracting " + rClass.getSimpleName() + " from CSV files."); 
        } 
       } catch (NoSuchFieldException e) { 
        Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e); 
       } catch (IllegalAccessException e) { 
        Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e); 

       } 
      } // Close if (nextLine.length >= 2) 
     } // Close while ((nextLine = reader.readNext()) != null) 
    } catch (FileNotFoundException e) { 
     Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e); 
    } catch (IOException e) { 
     Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e); 
    } catch (IllegalArgumentException e) { 
     Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e); 
    } 
} 

Creo que con alguna recursión simple estos métodos podrían modificarse para manejar cualquier objeto Java, pero para mí esto era adecuado.

0

A pesar de su respuesta tardía, me he enfrentado a este problema de exportar entidades de Java a CSV, EXCEL, etc. en varios proyectos, donde tenemos que proporcionar la función de exportación en la interfaz de usuario.

He creado mi propio marco liviano. Funciona con cualquier Java Beans, Sólo tiene que añadir anotaciones en los campos que desea exportar a CSV, Excel, etc.

Enlace: https://github.com/abhisoni96/export-entity

Cuestiones relacionadas