0

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.

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

3 Comments

"Trying to use the same file name for input and output will not work." Will it not work if the output destination was in a different directory?
@DevilsHnd C:\one\file.csv is a different file name than C:\two\file.csv
No, the file name (file.csv) is exactly the same. It's the path (C:\two\ ) to that file that is different.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.