1

I am writing a telephone directory program and need to store the entries in a CSV formatted file. However, I am having difficulty keeping the entries in order when adding. I was considering reading in the entire file to an array of entries and then write it back out when the program exists, but this seems inefficient. Is there a straightforward approach to adding entries to a sorted file?

SVN600
  • 61
  • 3
  • You must be using *some* data structure to store the entries in memory. Which one did you choose? If you're trying to operate on the CSV directly, you're doing it the hard way, even if going the data structure route "seems inefficient" to you. Load it up into a data structure, sort it however you like, write it to disk when you're done, and bask in the glory. – Robert Harvey Jul 07 '16 at 15:35
  • As of now I am immediately writing entries to the file when they are added. No entries are stored outside of the file. – SVN600 Jul 07 '16 at 15:38
  • How large is the file? – Robert Harvey Jul 07 '16 at 15:39
  • Several thousand entries, but I'm going to take your advice and just load it into an ArrayList – SVN600 Jul 07 '16 at 15:40
  • Unfortunately, inserting lines into existing files efficiently is fundamentally impossible on current file systems. See http://programmers.stackexchange.com/questions/237416/why-can-we-not-insert-into-files-without-the-additional-writes-i-neither-mean – Kilian Foth Jul 07 '16 at 16:28

2 Answers2

3

Your first instinct is correct: sort the entire thing in memory, then write it out. Performing line-oriented I/O to read and write the file will be far more inefficient than doing a bulk read and write of the entire file.

TMN
  • 11,313
  • 1
  • 21
  • 31
0

My two cents:

  • Don't save to a file.
  • Save to a SQLite database table
  • Create an index for that table
  • The SQLite library maintains the index sorted and reports are sorted even when the data is not.
  • You can programativally export to CSV whenever you want.
Tulains Córdova
  • 39,201
  • 12
  • 97
  • 154