Home > Software engineering >  How to replace a CSV file after removing a column in Java
How to replace a CSV file after removing a column in Java

Time:07-07

I am new to Java. I was successfully able to read my CSV file from my local file location and was able to identify which column needed to be deleted for my requirements. However, I was not able to delete the required column and write the file into my local folder. Is there a way to resolve this issue? I have used the following code:

    CSVReader reader = new CSVReader(new FileReader(fileName));
    String [] nextLine;
    while ((nextLine = reader.readNext()) != null) {
        System.out.println(nextLine[15]);
    }

All I would like to do is to remove the column having index 15 and write the file as a CSV file in my local folder.

CodePudding user response:

I'm assuming you're using the OpenCSV library.

In order to make your code work, you have to fix 2 issues:

  • You need a writer to write your modified CSV to. OpenCSV provides a CSVWriter class for this purpose.
  • You need to convert your line (which is currently a String array) into a list to be able to remove an element, then convert it back into an array to match what the CSVWriter.writeNext method expects.

Here's some code that does this:

CSVReader reader = new CSVReader(new FileReader(fileName));
CSVWriter writer = new CSVWriter(new FileWriter(outFileName));
String[] origLine;
while ((origLine = reader.readNext()) != null) {
    List<String> lineList = new ArrayList<>(Arrays.asList(origLine));
    lineList.remove(15);
    String[] newLine = lineList.toArray(new String[lineList.size()]);
    writer.writeNext(newLine, true);
}
writer.close();
reader.close();

Some additional remarks:

  • The code probably needs a bit more error handling etc if it's to be used in a production capacity.
  • List indices in Java start at 0, so remove[15] actually removes the 16th column from the file.
  • The code writes its output to a separate file. Trying to use the same file name for input and output will not work.
  • Related