【问题标题】:CSVWriter don't allow to write to fileCSVWriter 不允许写入文件
【发布时间】:2017-05-07 20:56:22
【问题描述】:

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

【问题讨论】:

  • 好吧,如果writeAll() 需要传递一个数组,你就不能直接传递一个列表。尝试先转换它,例如writer.writeAll(data.toArray( new String[] ).
  • 在这种情况下你不需要 for 循环,只需写 writer.writeAll(data.toArray(new String[]))

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


【解决方案1】:

试试这个:

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】:

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

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

    【讨论】:

    • 我从文件 resfile = new File(target)..... 开始删除了所有内容,然后放入您的代码。现在我得到了错误:没有找到合适的方法来 write(List[String])
    【解决方案3】:

    问题是

    writer.writeAll 接受String[] 作为输入,您传递的是List&lt;String&gt;

    改变

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


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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-23
      • 1970-01-01
      • 2011-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多