0

I have a non-trivial question for guys.

I seek to print some data to an existing .csv file. I am aware of the fact that FileWriter("c://Directory",true) prints in extension to a current .csv file. However, instead of appending to the last line in the .csv, do you know of a way to print in the existing .csv file, from the first line in the .csv but adding new columns to the existing lines in the existing csv file?

Example: myfile.csv contains:

c1; c2
a; b
d; e

now I want to add the following to the above file:

; c3
; c
; f

such that myfile.csv now containts:

c1; c2; c3
a; b; c
d; e; f

Is this even possible? Or perhaps the easiest way is to just create an entire new file?Thanks in advance for your time!

joragupra
  • 692
  • 1
  • 12
  • 23
SteewDK
  • 363
  • 1
  • 4
  • 14
  • 1
    [You can't insert data in the middle of a file](http://stackoverflow.com/questions/289965/inserting-text-into-an-existing-file-via-java) so you will need to overwrite the whole file. – assylias Jan 03 '14 at 13:43
  • @assylias thanks for your reply. I appreciate it very much! I guess i will need to overwrite the existing file with the same content. Thanks! – SteewDK Jan 03 '14 at 13:45

2 Answers2

1

You have to create an entire new file.

For CSV handling you can use some framework. I use this one.

karim
  • 15,408
  • 7
  • 58
  • 96
0

The problem is that each time you insert a new byte of data into the middle of a file, everything after that byte needs to be shuffled downwards. That can quickly become very expensive.

Your best bet will be to open a new file as your output, and then open your input.

Scan through your input streaming it to the output and making the required modifications as you go.

Once you are finished delete the original and move the temporary file into it's place.

Tim B
  • 40,716
  • 16
  • 83
  • 128