CSVWriter 不允许写入文件

CSVWriter don't allow to write to file

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

问题是

writer.writeAll 接受一个 String[] 作为输入,你正在传递一个 List<String>

改变

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


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

试试这个:

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,这会将您的列表多次打印到文件中。

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

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