javacsvjava.util.scannerfilewritercsv-write-stream

CSVWriter don't allow to write to file


I want to save my data into CSV file. I'm using Scanner to read -> CSVWriter to save.

I got error: incompatibile types: List[String] can't be converted to String[].

method:

private static void insertToFile(String source, String target)
{   
    List<String> data = new ArrayList<String>();
    try{
    Scanner sc = new Scanner(new File(source));

    while (sc.hasNextLine()) {
        data.add(sc.nextLine());
    }
    sc.close();
    }
    catch(Exception e){
    e.printStackTrace();
    }

       File resfile = new File(target);      

        try{
            CSVWriter writer = new CSVWriter(new FileWriter(resfile, true));

             //BufferedWriter bufferedWriter = new BufferedWriter(writer);

            for (String j : data) {
              //writer.writeAll(data);//error here
            }

               writer.close();
            }
        catch(Exception e){
                e.printStackTrace();
        }
    }

Solution

  • The problem is that

    writer.writeAll accept a String[] as input, you are passing a List<String>

    changing

    for (String j : data) {
       //writer.writeAll(data);//error here
    }
    

    to

    writer.writeAll(data.toArray(new String[data.size()])); will solve the issue.