我將數據追加到csv的最後一行。我想刪除現有的行,然後用附加的元素重寫它。有什麼方法可以刪除csv中的行嗎?我正在使用opencsv來讀取和寫入文件。我嘗試過使用CSVIterator類。但是,似乎迭代器不支持remove()操作。 這裏是我試過的代碼:刪除csv文件中的一行
static String[] readLastRecord(File outputCSVFile) throws WAGException {
checkArgument(outputCSVFile != null, "Output CSV file cannot be null");
FileReader fileReader = null;
CSVReader csvFileReader = null;
CSVIterator csvIterator = null;
String[] csvLastRecord = null;
try {
fileReader = new FileReader(outputCSVFile);
csvFileReader = new CSVReader(fileReader, ',', '\'',
csvRowCount - 1);
csvIterator = new CSVIterator(csvFileReader);
while (csvIterator.hasNext()) {
csvLastRecord = csvIterator.next();
csvIterator.remove();
}
} catch (IOException ioEx) {
throw new WAGException(
WAGInputExceptionMessage.FILE_READ_ERR.getMessage());
} finally {
try {
if (csvFileReader != null)
csvFileReader.close();
} catch (IOException ioEx) {
throw new WAGException(
WAGInputExceptionMessage.FILE_CLOSE_ERR.getMessage());
}
}
return csvLastRecord;
}
的API說'刪除()'*是*通過迭代器支持:HTTP: //opencsv.sourceforge.net/apidocs/當你寫「似乎迭代器不支持remove()操作」 - 你應該提供更多的細節:它不能編譯?它編譯但不運行?它運行但不做你想做的事情? – alfasin 2014-11-24 04:54:57
sourceforge.net上的實現說它不支持..它是一個只讀迭代器。 http://sourceforge.net/p/opencsv/source/ci/3ba1873ef55b014893cae73b015d2bcb55b7d5a4/tree/src/main/java/au/com/bytecode/opencsv/CSVIterator.java – user3453784 2014-11-24 04:59:12
在這種情況下 - 你必須閱讀所有的換行爲數據結構(列表可能已經足夠好了),刪除你想要的行並覆蓋(重寫)文件。 – alfasin 2014-11-24 05:01:27