Java: CSV File Easy Read/Write

后端 未结 3 506
一向
一向 2020-11-27 23:02

I\'m working on a program that requires quick access to a CSV comma-delimited spreadsheet file. So far I\'ve been able to read from it easily using a BufferedReader. However

相关标签:
3条回答
  • 2020-11-27 23:26

    Rather than reinventing the wheel you could have a look at OpenCSV which supports reading and writing of CSV files. Here are examples of reading & writing

    0 讨论(0)
  • 2020-11-27 23:36

    Please consider Apache commons csv. To fast understand the api, there are four important classes:

    CSVFormat

    Specifies the format of a CSV file and parses input.

    CSVParser

    Parses CSV files according to the specified format.

    CSVPrinter

    Prints values in a CSV format.

    CSVRecord

    A CSV record parsed from a CSV file.

    Code Example:

    Unit test code:

    0 讨论(0)
  • 2020-11-27 23:36

    The spreadsheet contains names, phone numbers, email addresses, etc. And the program lists everyone's data, and when you click on them it brings up a page with more detailed information, also pulled from the CSV. On that page you can edit the data, and I want to be able to click a "Save Changes" button, then export the data back to its appropriate line in the CSV--or delete the old one, and append the new.

    The content of a file is a sequence of bytes. CSV is a text based file format, i.e. the sequence of byte is interpreted as a sequence of characters, where newlines are delimited by special newline characters.

    Consequently, if the length of a line increases, the characters of all following lines need to be moved to make room for the new characters. Likewise, to delete a line you must move the later characters to fill the gap. That is, you can not update a line in a csv (at least not when changing its length) without rewriting all following lines in the file. For simplicity, I'd rewrite the entire file.

    Since you already have code to write and read the CSV file, adapting it should be straightforward. But before you do that, it might be worth asking yourself if you're using the right tool for the job. If the goal is to keep a list of records, and edit individual records in a form, programs such as Microsoft Access or whatever the Open Office equivalent is called might be a more natural fit. If you UI needs go beyond what these programs provide, using a relational database to keep your data is probably a better fit (more efficient and flexible than a CSV).

    0 讨论(0)
提交回复
热议问题