[java] How to serialize object to CSV file?

I want to write a Object into CSV file. For XML we have XStream like this
So if i want to convert object to CSV do we have any such library ?

EDIT: I want to pass my list of Bean to a method which should write all the fields of bean to CSV.

This question is related to java serialization csv object

The answer is


I wrote a simple class that uses OpenCSV and has two static public methods.

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);
    }
}

I think with some simple recursion these methods could be modified to handle any Java object, but for me this was adequate.


It would be interesting to have a csv serializer as it would take up the minimal space compared to other serializing method.

The closest support for java object to csv is stringutils provided by spring utils project

arrayToCommaDelimitedString(Object[] arr) but it is far from being a serializer.

Here is a simple utility which uses reflection to serialize value objects

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;
}

}

Here is an example value object

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;
}

}

and the code to run the 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);
}

}

Output:

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

Though its very late reply, I have faced this problem of exporting java entites to CSV, EXCEL etc in various projects, Where we need to provide export feature on UI.

I have created my own light weight framework. It works with any Java Beans, You just need to add annotations on fields you want to export to CSV, Excel etc.

Link: https://github.com/abhisoni96/dev-tools


For easy CSV access, there is a library called OpenCSV. It really ease access to CSV file content.

EDIT

According to your update, I consider all previous replies as incorrect (due to their low-levelness). You can then go a completely diffferent way, the hibernate way, in fact !

By using the CsvJdbc driver, you can load your CSV files as JDBC data source, and then directly map your beans to this datasource.

I would have talked to you about CSVObjects, but as the site seems broken, I fear the lib is unavailable nowadays.


Worth mentioning that the handlebar library https://github.com/jknack/handlebars.java can trivialize many transformation tasks include toCSV.



You can use gererics to work for any class

public class FileUtils<T> {
public String createReport(String filePath, List<T> t) {
    if (t.isEmpty()) {
        return null;
    }

    List<String> reportData = new ArrayList<String>();

    addDataToReport(t.get(0), reportData, 0);

    for (T k : t) {
        addDataToReport(k, reportData, 1);
    }
    return !dumpReport(filePath, reportData) ? null : filePath;
}

public static Boolean dumpReport(String filePath, List<String> lines) {
    Boolean isFileCreated = false;

    
    String[] dirs = filePath.split(File.separator);
    String baseDir = "";
    for (int i = 0; i < dirs.length - 1; i++) {
        baseDir += " " + dirs[i];
    }
    baseDir = baseDir.replace(" ", "/");
    
    File base = new File(baseDir);
    base.mkdirs();

    File file = new File(filePath);
    try {
        if (!file.exists())
            file.createNewFile();
    } catch (Exception e) {
        e.printStackTrace();
        return isFileCreated;
    }

    try (BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(file), System.getProperty("file.encoding")))) {
        for (String line : lines) {
            writer.write(line + System.lineSeparator());
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

void addDataToReport(T t, List<String> reportData, int index) {
    String[] jsonObjectAsArray = new Gson().toJson(t).replace("{", "").replace("}", "").split(",\"");
    StringBuilder row = new StringBuilder();

    for (int i = 0; i < jsonObjectAsArray.length; i++) {
        String str = jsonObjectAsArray[i];
        str = str.replaceFirst(":", "_").split("_")[index];

        if (i == 0) {
            if (str != null) {
                row.append(str.replace("\"", ""));
            } else {
                row.append("N/A");
            }
        } else {
            if (str != null) {
                row.append(", " + str.replace("\"", ""));
            } else {
                row.append(", N/A");
            }
        }
    }
    reportData.add(row.toString());
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to serialization

laravel Unable to prepare route ... for serialization. Uses Closure TypeError: Object of type 'bytes' is not JSON serializable Best way to save a trained model in PyTorch? Convert Dictionary to JSON in Swift Java: JSON -> Protobuf & back conversion Understanding passport serialize deserialize How to generate serial version UID in Intellij Parcelable encountered IOException writing serializable object getactivity() Task not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objects Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Examples related to csv

Pandas: ValueError: cannot convert float NaN to integer Export result set on Dbeaver to CSV Convert txt to csv python script How to import an Excel file into SQL Server? "CSV file does not exist" for a filename with embedded quotes Save Dataframe to csv directly to s3 Python Data-frame Object has no Attribute (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape How to write to a CSV line by line? How to check encoding of a CSV file

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor