【发布时间】:2016-11-10 05:07:29
【问题描述】:
我的代码的目标是用用户输入的文本字段替换 .CSV 文件中的某个文本值。
我的 .CSV 文件包含用逗号分隔的值:hey,hi。如果我只是想替换“嘿”,那么我会从文本字段中收集输入并将“嘿”替换为“再见”。输出:bye,hi。
在我的代码中,我相信我正在读取我的文件并将文件的内容写入一个列表,以逗号分隔。
然后我将遍历列表并将列表中用户输入的一个实例替换为另一个用户输入并将其写回文件。
但是,我无法将它写回文件,因为我收到 Object[] cannot be convert to String[] 错误。因此,我不知道如何替换文本文件中的用户输入实例。
这是我的代码:
try{
//Convert user input into strings
String strSerial = editSerialField.getText();
String strLocation = editLocationField.getText();
//Read existing file
CSVReader reader = new CSVReader(new FileReader("test test.txt"), ',');
List myEntries = reader.readAll();
//Iterate through my array
for (int i = 0; i < myEntries.size(); i++)
{
//If an entry matches the user input
if (myEntries.get(i).equals(strSerial))
{
//Set the match to the user input from strLocation
myEntries.set(i, strLocation);
break;
}
}
//Write to existing file
CSVWriter writer = new CSVWriter(new FileWriter("test test.txt"), ',');
//Error is here**********************
//Write the new string with the replaced word OVER the same file
writer.writeNext(myEntries.toArray(new String[myEntries.size()]));
writer.close();
}catch (IOException e)
{
System.out.println(e);
}
}
如何修改我的代码,以便将我的更改写入 .CSV 文件?
【问题讨论】:
-
使用泛型修改 myEntries 变量,如下所示。 List
myEntries = reader.readAll();
标签: java arrays list csv opencsv