debal
debal

Reputation: 1017

Create an array of strings and a string variable from dynamic args

I am trying to achieve inputting n number of parameters as arguments to the java main function.

From these n parameters, n-1 of them are input file and the nth one is output file.

public static void main(String[] args) {

    List<String> stringList = new ArrayList<String>();
    String xlsxFileAddress;
    for (int i = 0; i < args.length - 1; i++) {
        stringList.add(args[i].toString());
    }
    String[] csvFileAddress = (String[]) stringList.toArray();

    xlsxFileAddress = args[args.length - 1];
    for (int i = 0; i < 2; i++) {
        System.out.println(csvFileAddress[i]);
    }

    System.out.println(xlsxFileAddress);
    csvToXLSX(csvFileAddress, xlsxFileAddress);
}

But this is throwing the following error -

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
    at com.jcg.csv2excel.CsvToExcel.main(CsvToExcel.java:109)

Upvotes: 1

Views: 64

Answers (4)

Sunil Dabburi
Sunil Dabburi

Reputation: 1472

Two approaches to your problem

using toArray()

String[] csvFileAddress = stringList.toArray(new String[0])

using stream()

String[] csvFileAddress = stringList.stream().toArray(String[]::new)

Upvotes: 0

SELA
SELA

Reputation: 6793

toArray() will returns an Object[], regardless of generics. You could use the overloaded variant instead.

Use the following :

String[] csvFileAddress =stringList.toArray(new String[stringList.size()]);

Upvotes: 0

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 235984

You need to use the toArray() overloaded version that takes an array, this will indicate the proper type of the array to build so you won't have the class cast exception. Try this instead:

 String[] csvFileAddress = stringList.toArray(new String[stringList.size()]);

Upvotes: 3

You need to specify the array type and size when you try to convert a list to array.

String[] csvFileAddress =stringList.toArray(new String[stringList.size()]);

Upvotes: 2

Related Questions