PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 27, 2022

[FIXED] How to create a csv file from ConcurrentHashMap<String, Integer> in Java?

 August 27, 2022     concurrenthashmap, csv, filewriter, for-loop, java     No comments   

Issue

I need to create a single string named CSVOutput, and load all keys and values from the ConcurrentHashMap<String, Integer>, counts into this file separated by commas. So I'll have two columns in the resulting csv file, one is for the keys and the other one for the values.

I have written this code for my method OutputCountsAsCSV:

private void OutputCountsAsCSV(ConcurrentHashMap<String, Integer> counts, String filename) {
    String CSVOutput = new String("");
    for (Entry<String, Integer> entry : counts.entrySet()) {
        String rowText = String.format("%s,%d\n", entry.getKey(), entry.getValue());  # defines new lines/rows
        CSVOutput += rowText;
        try (FileWriter writer = new FileWriter(filename)) {
            writer.write(CSVOutput);
        }
        catch (Exception e) {
            System.out.println("Saving CSV to file failed...");
        }
    }
    System.out.println("CSV File saved successfully...");
}

However, I'm told I should have followed this order:

  1. create and prepare file
  2. for each entry, write data to file
  3. close the file (and print that it happened successfully).

Indeed, my System.out.println("CSV File saved successfully...") seems to be inside the loop and is being printed many times.

How can I do it correctly?

I am a beginner in Java, so I'm very grateful for any help.


Solution

Here is a better approach (do your own research about the finally keywords)

private void OutputCountsAsCSV(ConcurrentHashMap<String, Integer> counts, String filename) {
            
    try (FileWriter writer = new FileWriter(filename)) {
        
        for (Entry<String, Integer> entry : counts.entrySet()) {
            
            String rowText = String.format("%s,%d\n", entry.getKey(), entry.getValue());  
            writer.append(rowText);
        }
    
    } catch (Exception e) {
        System.out.println("Saving CSV to file failed...");
    } finally {
        System.out.println("CSV File saved successfully...");      
    } 
}


Answered By - qdoot
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing