我的代碼的目標是將我的.CSV文件中的某個文本值替換爲用戶輸入的文本字段。對象[]無法轉換爲字符串[]
我的.CSV文件的值由逗號分隔:hey,hi
。如果我只是想替換'嘿',那麼我會從文本字段中收集輸入,並用'再見'代替'hey'。輸出:bye,hi
。
在我的代碼中,我相信我正在閱讀我的文件,並將文件的內容寫入列表中,並用逗號分隔。
然後,我將遍歷列表,並將列表中用戶輸入的實例替換爲另一個用戶輸入並將其寫回文件。
但是,我無法將它寫回文件,因爲我得到Object []無法轉換爲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變量,如下所示。 列表 myEntries = reader.readAll(); –
dammina