我想把我的数据保存到CSV文件中。我用扫描仪来读取-> CSVWriter来保存。
我得到了错误:不兼容类型: ListString不能转换为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();
}
}发布于 2016-12-22 09:30:17
问题是
writer.writeAll接受String[]作为输入,您将传递一个List<String>
改变
for (String j : data) {
//writer.writeAll(data);//error here
}至
writer.writeAll(data.toArray(new String[data.size()]));将解决这个问题。
发布于 2016-12-22 09:31:39
有一个简单的方法,您可以使用下面提到的代码。在代码中导入这些依赖项(导入java.io.File,导入java.io.FileWriter)。
FileWriter writer = new FileWriter(new File(File_path));
writer.write(data);
writer.close();发布于 2016-12-22 09:31:29
试一试:
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,这会多次将列表打印到文件中。
https://stackoverflow.com/questions/41279642
复制相似问题