0

I am trying to read a HashMap and write to a CSV file. I am using CSVPrinter, but my method is not returning a CSV file.

This is the code I use: Edited Code

   import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVPrinter;

public class SJV{
    public File writeCSV(Map featureSet) throws IOException{

        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
        Map<String, Integer> map = featureSet;
        File temp = File.createTempFile("tempfile", ".tmp");
        FileWriter fs = new FileWriter(temp);

        CSVPrinter csvFilePrinter = new CSVPrinter(fs, csvFileFormat);
        //csvFilePrinter.printRecord(FILE_HEADER);

        csvFilePrinter.printRecord(map.keySet().toArray());
        csvFilePrinter.printRecord(map.values().toArray());



csvFilePrinter.close();
fs.close();


        return  temp;
    }
}

This is the test I have:

public void testWriteCSV() throws IOException {
    SJV sj = new  SJV();

    HashMap<String, Integer> hmap = new HashMap<String, Integer>();
    hmap.put("Feature1", 1);
    hmap.put("Feature2", 2);
    File fs = sj.writeCSV(hmap);

    if (fs.exists()){
        Scanner input = new Scanner(fs );

        while (input.hasNextLine())
        {
           System.out.println(input.nextLine());
        }
        input.close();
    }

I really don't understand why the method is not returning a CSV file.

10
  • A bit of code is missing. What is sj? Is anything written? Any errors? Commented Jun 6, 2017 at 10:47
  • What is the method returning instead of a CSV file? Commented Jun 6, 2017 at 10:48
  • 2
    I don't think you're closing the file. Commented Jun 6, 2017 at 10:54
  • 3
    @Kumaresp No, actually, it isn't another problem. It is probably the reason for the problem you have. Try correcting it. Commented Jun 6, 2017 at 10:56
  • 2
    Please edit your question and put your new version with the close. Commented Jun 6, 2017 at 11:04

2 Answers 2

2

Try this (In this code I have changed the format from .tmp to .csv)

One problem was we were not closing the csvFilePrinter -> csvFilePrinter.close() and what I understood from the question is that the user is expecting a CSV file extension , so , I have used .csv extension while writting it . :

    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Scanner;

    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVPrinter;

    public class TestMain {

        public static void main(String args[]) {

            HashMap<String, Integer> hmap = new HashMap<String, Integer>();
            hmap.put("Feature11", 1);
            hmap.put("Feature22", 2);
            CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(System.lineSeparator());
            Map<String, Integer> map = hmap;
            File temp;
            try {
                temp = File.createTempFile("tempfile", ".csv");
                FileWriter fs = new FileWriter(temp);

                CSVPrinter csvFilePrinter = new CSVPrinter(fs, csvFileFormat);
                csvFilePrinter.printRecord(map.keySet().toArray());
                csvFilePrinter.printRecord(map.values().toArray());
                csvFilePrinter.close();

                System.out.println(" temp " + temp);

                if (temp.exists()) {
                    Scanner input = new Scanner(temp);

                    while (input.hasNextLine()) {
                        System.out.println(input.nextLine());
                    }
                    input.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

Edited as per the suggestions in comment (This code works for me and here is the sample output) :

 temp C:\Users\<MY USERNAME>\AppData\Local\Temp\tempfile7124969351872886823.csv
Feature11,Feature22
1,2
Sign up to request clarification or add additional context in comments.

1 Comment

Might be a good idea to not throw the IOException and do a try/catch on it yourself..
0

Try:

fs.flush();
fs.close();
csvFilePrinter.close();

3 Comments

There is no need for flush before close. Also no need to close the FileWriter before closing the CSVPrinter (if CSVPrinter has close()).
The fs.close() will close fs before anything buffered inside the csvFilePrinter is flushed. Then when you try to close csvFilePrinter nothing will happen before fs is already closed.
you have verified the file is empty, and not merely checking it inside the code, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.