juiceb0xk juiceb0xk - 25 days ago 12
Java Question

Object[] cannot be converted to String[]

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?

Answer

For a start writeNext will write on line at a time, so you need to loop.

Secondly consider using not a raw List but using generics.

Thirdly, it may be cleaner to write as you go

and lastly, each line will contain an Array of Strings

consider this code (not tested)

        CSVReader reader = new CSVReader(new FileReader("test test.txt"), ',');
        List<String []> myEntries = reader.readAll();
        reader.close ();

        CSVWriter writer = new CSVWriter(new FileWriter("test test.txt"), ',');

        //Iterate through my array
        for (String [] line : myEntries)
        {
            ArrayList<String> newLine = new ArrayList <String>();
            for (String word : line) {
            {
                String newVal = word.replace(strSerial, strLocation);
                newLine.add (newVal);
            }
            writer.writeNext(newLine.toArray(new String[newLine.size()]));
        }
Comments