How to serialize object to CSV file?

前端 未结 8 1279
执念已碎
执念已碎 2020-11-27 17:14

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 w

8条回答
  •  [愿得一人]
    2020-11-27 18:01

    You can use gererics to work for any class

    public class FileUtils {
    public String createReport(String filePath, List t) {
        if (t.isEmpty()) {
            return null;
        }
    
        List reportData = new ArrayList();
    
        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 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 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());
    }
    

提交回复
热议问题