1

我想将我的数据保存到 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();
        }
    }
4

3 回答 3

1

问题是

writer.writeAll接受 aString[]作为输入,您正在传递 aList<String>

改变

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


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

于 2016-12-22T09:30:17.150 回答
1

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

FileWriter writer = new FileWriter(new File(File_path));
writer.write(data);
writer.close();
于 2016-12-22T09:31:39.757 回答
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列表中的每个元素调用整个列表,这会将您的列表多次打印到文件中。

于 2016-12-22T09:31:29.270 回答