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?

  • 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. Jul 7, 2016 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 7, 2016 at 15:38
  • How large is the file? Jul 7, 2016 at 15:39
  • Several thousand entries, but I'm going to take your advice and just load it into an ArrayList
    – SVN600
    Jul 7, 2016 at 15:40
  • Unfortunately, inserting lines into existing files efficiently is fundamentally impossible on current file systems. See programmers.stackexchange.com/questions/237416/… Jul 7, 2016 at 16:28

2 Answers 2


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.


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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.