简体   繁体   中英

How do I parse through a CSV (comma separated file) and display output

Does anyone know how I would go about creating an application that will go through a comma separated file (CSV) and organize that information and subsequently put that into a database? For example, I have to go through a file that looks like this:

Name of Athlete, Birthday, Salary($)
John Morris, 9/25/1991, 5000000 
Mike Hawk, 2/2/1988, 1000000
Dewayne Johnson, 11/22/1985, 4000000

etc.

How would I organize this information and set it up? I am trying to make it so I can ask the user for input. For example: have the user enter "a" for amount of salary and output all the players who make that EXACT amount of money.

Player 1 name, Player 1 birthday Player 2 name, Player 2 birthday

Any help is appreciated. I would appreciated help with reading the information and storing/retrieving it.

Don't give me the complete answer. I am a student learning this and I want to understand it.

I would think about these steps:

  • Create a class to map with the data in your CSV. For example, an Athlete class with attributes name , birthday and salary (it's up to you define each data type).
  • Read the CSV file. You can use Scanner or BufferedReader (using a FileReader ) to accomplish this.
  • For each line read:
    • Split the string into several strings by comma (,)
    • Create a new Athlete object and parse each string into an attribute to set it into the object.
    • Store the new Athlete in a collection ( List or something).
  • Once you completed loading a number of Athlete s, save them into your database.
  • Repeat this until you finish reading the csv.

Splitting by a comma is a naive way of dealing with CSV. Unless you are 100% sure you will never have a comma in an actual field, then go this route, but if you may ever encounter a string like hello, my name is devshorts , you should use a CSV library. http://opencsv.sourceforge.net/ seems to be a good choice.

Once thats done, map each entry to a class that represents what a line is. Make an Atheltes class, where it has fields for Name , Birthdate , and Salary .

You can use a direct JDBC connection to a sqlite/mysql/whatever database and insert (using raw SQL) the values into a table called Atheletes . If you want to use an ORM go with hibernate, but that may be more work than you need to set up.

Well a simple way of reading this type of files would be using a BufferedReader that allows you to read the file line by line.

Then use split function to separate the string by delimiter and convert it into an array.

With the resulting array you can insert data into the database making proper conversion as required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM