Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete a row in csv file

Tags:

java

opencsv

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;
    }
like image 677
user3453784 Avatar asked Nov 24 '14 04:11

user3453784


1 Answers

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

like image 74
Wladislaw Avatar answered Nov 04 '22 06:11

Wladislaw