-2

I have a CSV file in my local folder. I would like to read it, remove a column, and replace the file in the same folder.

Actual sample data:

ID,EMAIL,FIRSTNAME,LASTNAME             
99999,TestEmail@fakeemail.com,TEST_FNAME,TEST_LNAME
33333,TestEmail@fakeemail.com,TEST_FNAME,TEST_LNAME

Expected data from the sample data:

ID,EMAIL,FIRSTNAME             
99999,TestEmail@fakeemail.com,TEST_FNAME
33333,TestEmail@fakeemail.com,TEST_FNAME

In this case, I would like to remove the column LASTNAME. Can it be done effectively in Java?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
ychaulagain
  • 73
  • 1
  • 8

1 Answers1

0

As in your example, you want to remove last column. So easiest way would be to substring from beginning to last index of separator ,.

line.substring(0,line.lastIndexOf(","))

Full example:

try(PrintWriter pw = new PrintWriter(Files.newBufferedWriter(
                     Paths.get("path_to_output_file")))) {
    Files.lines(Paths.get("path_to_input_file")).map(line ->    line.substring(0,line.lastIndexOf(","))).forEach(pw::println);
}

If you need to remove other column, you may you split line.split(",") and than concatenate skipping column you want.

Dorin Simion
  • 131
  • 5
  • 1
    It's dangerous (and often wrong) to split CSV lines using `String.split`. The lines can be like `column one,column two,"column three,not four","column four,not three"`. A simple `String.split` would treat such data incorrectly. Use a proper CSV parser instead. – k314159 Jul 18 '22 at 15:05