Search code examples
csvgroovyconcurrenthashmap

Getting empty CSV files


I am trying to write hashmap data into CSV files but I see empty files being generated. Here is the following code that I am using:

String fileName
    for (String key : concurrentHashMap.keySet()) {
        logInfo(key + ": ")//gives the name of the file
        logInfo("concurrentHashMapKey" + concurrentHashMap.get(key))
        fileName = key
        logInfo("fileName: " + fileName)
        helpers.writeHashMapToCsv(concurrentHashMap, fileName)
    }

public void writeHashMapToCsv(ConcurrentHashMap<String, String> collectedCSV, String fileName) throws Exception {
        String eol = System.getProperty("line.separator")
        try{
            Writer writer = new FileWriter(".\\baseline-files\\" + fileName)
            for (Map.Entry<String, String> entry : collectedCSV.entrySet()) {
                println "entry = $entry"
                writer.append(entry.getKey())
                        .append(',')
                        .append(entry.getValue())
                        .append(eol)
            }
        } catch (IOException ex ) {
            ex.printStackTrace(System.err)
        }
    }

Can someone help me what am I doing wrong here?

Note: concurrentHashMap Size =2

concurrentHashMap = [NetworkLeakage_Main_crosstab.csv: % of Total Total Payments No Pro along Serv Netwk, Site Type Total Payments No Pro Home Health Out Of Network 1% $247,870 Home Health Owned 6% $1,306,259 Skilled Nursing Facility Out Of Network 4% $860,545 Skilled Nursing Facility Owned 18% $3,919,193 , IP_RehabSNF_Profiles_crosstab.csv:Facility Site Type Network Affiliation Number of Episodes Total Payment % of Total Payment Mean Episode Payment ALOS CMS Rating LORRETTA HOSPITAL Anchor Owned 28 $344,392 2% $12,300 3
LORRETTA HOSPITAL Home Health Out Of Network 87 $14,358 0% $2,872
LORRETTA HOSPITAL Home Health Owned 19 $2,981 0% $2,981
LORRETTA HOSPITAL Outpatient Out Of Network 77 $3,706 0% $71
LORRETTA HOSPITAL Outpatient Owned 1,593 $149,194 1% $288
]

So there are 2 sets of keys (file names) and values (data) present here for which I need to genereate follwoing 2 files: 1. NetworkLeakage_Main_crosstab.csv

  1. IP_RehabSNF_Profiles_crosstab.csv

Solution

  • Add writer.close() as your Writer buffers data.

    It is best to add it to the finally block:

    } catch (IOException ex) {
        ex.printStackTrace(System.err)
    } finally {
        writer.close();
    }