The goal of my code is to replace a certain text value within my .CSV file with the user input of a text field.
My .CSV file has values delimited by commas: hey,hi
. If I'm just wanting to replace 'hey' then I would gather the input from the text field and replace 'hey' with 'bye'. Output: bye,hi
.
In my code, I believe I am reading in my file and writing the contents of the file to a list, delimited by commas.
I will then iterate through the list and replace an instance of the user input within the list, with another user input and write it back to file.
However, I cannot write it back to file as I'm getting the Object[] cannot be converted to String[] error. Thus I'm stuck as to how to replace the instance of user input within the text file.
Here's my code:
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);
}
}
How do I modify my code so that it writes my changes to the .CSV file?