CSVWriter不允许写入文件

时间:2016-12-22 09:21:38

标签: java csv java.util.scanner filewriter csv-write-stream

我想将数据保存到CSV文件中。我正在使用Scanner阅读 - > CSVWriter保存。

我收到错误:不兼容的类型:List [String]无法转换为String []。

方法:

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();
        }
    }

3 个答案:

答案 0 :(得分:1)

问题在于

writer.writeAll接受String[]作为输入,您传递List<String>

改变

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


writer.writeAll(data.toArray(new String[data.size()]));将解决问题。

答案 1 :(得分:0)

请改为尝试:

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

    // utilize Scanner implementing AutoCloseable and try-with-resource construct 
    // see https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html )
    try (Scanner sc = new Scanner(new File(source))) {
        while (sc.hasNextLine()) {
            data.add(sc.nextLine());
        }
    }
    catch (Exception e){
        e.printStackTrace();
    }

    File resfile = new File(target);

    try {
        // depending on the CSVWriter implementation consider using try-with-resource as above
        CSVWriter writer = new CSVWriter(new FileWriter(resfile, true));

        writer.writeAll(data.toArray(new String[data.size()]));

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

它将列表转换为初始化为列表长度的数组。此外,您可能不希望在列表中的每个元素的整个列表中调用writeAll,这会将您的列表多次打印到您的文件中。

答案 2 :(得分:0)

有一种简单的方法,您可以使用下面提到的代码。 在代码中导入这些依赖项(import java.io.File,import java.io.FileWriter)。

FileWriter writer = new FileWriter(new File(File_path));
writer.write(data);
writer.close();