delete a row in csv file

user3453784 picture user3453784 · Nov 24, 2014 · Viewed 15.8k times · Source

I am appending the data to the last row of a csv. I wanted to delete the existing row and then rewrite it with the appended element. Is there any way of deleting the row in csv? I am using opencsv to read and the write the file. I tried using CSVIterator class. However, it seems the iterator does not support the remove() operation. Here is the code that I tried:

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;
    }

Answer

Wladislaw picture Wladislaw · May 15, 2016

i just found an answer. Hope it helps.

You need to read the csv, add elements to the list string, remove specific row from it with allelements.remove(rowNumber) and then write the list string back to the csv file.

The rowNumber is an int with row number.

CSVReader reader2 = new CSVReader(new FileReader(filelocation));
List<String[]> allElements = reader2.readAll();
allElements.remove(rowNumber);
FileWriter sw = new FileWriter(filelocation);
CSVWriter writer = new CSVWriter(sw);
writer.writeAll(allElements);
writer.close();

Look at this example from opencsv opencsv example