Skip to content
Advertisement

Java Export Arrays$ArrayList to csv

I’m going to do a Java library on a simple data frame that can read CSV files, edit the CSV and export CSV file. My problem is on how to export it.
Here is how I read my CSV file:

String line;
List dataFrame = new ArrayList();
String filePath = "C:\Users\user\Desktop\SimpleDataFrame\src\Book1.csv";

try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
    while ((line = br.readLine()) != null) {
         List values = Arrays.asList(line.split(String.valueOf(",")));
         dataFrame.add(values);
      }
 } catch (Exception e) {
         System.out.println(e);
 }

And this is how I implement the write CSV file:

 FileWriter writer = new FileWriter(new File("Book2.csv"));
 for(int i = 0; i<dataFrame.size(); i++){
     String[] array = (String [])dataFrame.get(i);
     for(int j = 0; j<array.length; j++){
         writer.write(array[j]);
         if(j<array.length-1) writer.write(",");
         else writer.write("n");
     }
 }

And this is the exception that it throws to me:

Exception in thread "main" java.lang.ClassCastException: class java.util.Arrays$ArrayList cannot be cast to class [Ljava.lang.String; (java.util.Arrays$ArrayList and [Ljava.lang.String; are in module java.base of loader 'bootstrap')

Can I know what is the problem?

Advertisement

Answer

The problem here is your use of rawtypes. Lists in java are generic, and you have to specify the element type you want to use. Also, Lists are not interchangeable with arrays, and cannot directly cast to arrays.

List dataFrame = new ArrayList();

should trigger a warning, and you should not ignore this warning.

Based on your usage, it has to be a

List<List<String>> dataFrame = new ArrayList<>();

The elements are Lists, because you explicitly convert them from arrays to Lists in

List values = Arrays.asList(line.split(String.valueOf(",")));

String.split returns a String[], which you convert to a List with Arrays.asList.

This line should be

List<String> values = Arrays.asList(line.split(","));

(you don’t need String.valueOf here, the literal is already a String).

And then in

String[] array = (String [])dataFrame.get(i);

you get a runtime exception because dataFrames contains Lists, not arrays String[]. This can be rewritten as, for example using enhanced for loop and String.join, and wrapping the writer in a try-with-resources, so that you can’t forget closing it.

try (FileWriter writer = new FileWriter(new File("Book2.csv"))) {
    for (List<String> list : dataFrame) {
        writer.write(String.join(",", list));
        writer.write("n");
    }
} catch (IOException e) {
    e.printStackTrace();
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement