1

I have a method called createCSV where I convert a List into a csv file. I want to use a pathname for the new file with the name of the List, which I give as a param. How can i do this? Here is my code:

public static File createCSV(List<String[]> custList) {

    String methodName = "createCSV";
    String csv = "/home/oracle/outputcsv/" + custList + ".csv"; // pathname
                                                                // with
                                                                // listname.csv
    File file = new File(csv);

    try {
        custList = new ArrayList<String[]>();

        FileWriter filewr = new FileWriter(file);
        CSVWriter writer = new CSVWriter(filewr);

        custList.add(0, new String[] { "customerId" });

        for (String[] list : custList) {

            custList.add(0, new String[] { "customerId" });

        }

        writer.writeAll(custList);
        logger.debug("[{}] custlist = {}", methodName, custList);

        logger.debug("[{}]CSV written successfully", methodName);
        writer.close();

        logger.debug("[{}]The file is supposed to be :) : {} ", methodName,
                file);
        // return file;

    } catch (IOException e) {
        e.printStackTrace();
        logger.debug("[{}] IOException {}", methodName, e);
    }

    return file;

}

I also have a problem in displaying all my list elements. I tried to use a for statement but it didn't help.

Thanks a lot!

Razvan N
  • 554
  • 3
  • 9
  • 29

3 Answers3

2

What you’re asking for is not possible in Java. The parameter names are not retained; because what name would you give an argument of 1, or new Object()?

However, simply add a second parameter to your method:

public static File createCSV(List<String[]> custList, String filename) {
    …
}
Bombe
  • 81,643
  • 20
  • 123
  • 127
  • That was it, thank you very much! Furthermore, can you tell me what am I doing wrong in the parsing of the List? Because only one parameter is written, yet i have more in the List. – Razvan N Nov 20 '13 at 15:57
2

custlist is your list and you want a String to concatenate to your csv path. Add the list name as a parameter to your method.

createCSV(List<String[]> custList, String yourListName) 

then

String csv = "/home/oracle/outputcsv/" + yourListName + ".csv";
reese
  • 99
  • 8
0

In addition to the solution presented by Veronica and Bombe. If you are unwilling to type in the parameter name, you could try to recover it using techniques discussed here: Java Reflection: How to get the name of a variable?

Community
  • 1
  • 1
Rhand
  • 901
  • 7
  • 20