Skip to content
Advertisement

while Converting Object[] to String[] iam getting java.lang.ArrayStoreException for the following code

public void createCSV(Map<String, Object> map) {
   String  reportPath =  "C:/Users/nandini/Desktop/file.csv";

    try {
        FileWriter fileWriter = new FileWriter(reportPath);
        CSVWriter csvWriter = new CSVWriter(fileWriter,
                CSVWriter.DEFAULT_SEPARATOR,
                CSVWriter.NO_QUOTE_CHARACTER,
                CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                CSVWriter.DEFAULT_LINE_END);


        String[] header = map.keySet().toArray(new String[map.size()]);
        


        Object[] data = map.values().toArray(new Object[map.size()]);
        String[] stringArray = Arrays.copyOf(data, data.length, String[].class);

        // adding data to csv
        csvWriter.writeNext(header);
        csvWriter.writeNext(stringArray);            
        csvWriter.close();
    } catch (Exception e) {
        logger.error(e);

    }
}

Advertisement

Answer

This happens due to the following line:

String[] stringArray = Arrays.copyOf(data, data.length, String[].class);

The method Javadoc states that the method throws an ArrayStoreException if an element copied from original is not of a runtime type that can be stored in an array of class newType.

So if the Object[] array contains an element that is not a String, this exception will be thrown. Instead of casting the element to a String, you can get its string representation using the toString() method:

String[] stringArray = Arrays.stream(data)
                             .map(Object::toString)
                             .toArray(size -> new String[size]);

EDIT:

Without streams…

String[] stringArray = new String[data.length];
for (int i = 0; i < data.length; i++) {
    stringArray[i] = data[i].toString();
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement