Last active
August 29, 2015 13:58
-
-
Save ashleywxwx/9996695 to your computer and use it in GitHub Desktop.
How to read a CSV from a file, by label using Ostermiller.util.LabeledCSVParser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.io.File; | |
| import java.io.FileInputStream; | |
| import java.io.IOException; | |
| import java.io.InputStreamReader; | |
| import com.Ostermiller.util.CSVParser; | |
| import com.Ostermiller.util.LabeledCSVParser; | |
| /** | |
| * Opens a csv file, grabs the label, and fetches fields via label names. | |
| * | |
| * @author Andrew Bell www.recursivechaos.com | |
| */ | |
| public class CSVParserExample | |
| { | |
| public static void main( String[] args ) throws IOException | |
| { | |
| // create File of file to open | |
| File file = new File("C:\\Workspace\\tablerage\\testdata\\test1.csv"); | |
| // fetch parser to manipulate data | |
| LabeledCSVParser lcsvp = getLabeledParser(file); | |
| // display labels | |
| String[] labels = lcsvp.getLabels(); | |
| for(String label:labels){ | |
| System.out.println("Label: " + label); | |
| } | |
| // iterate through rows, display contents by label | |
| while(lcsvp.getLine() != null){ | |
| System.out.println( | |
| "Number: " + lcsvp.getValueByLabel("Alpha") | |
| ); | |
| System.out.println( | |
| "Money: " + lcsvp.getValueByLabel("Bravo") | |
| ); | |
| System.out.println( | |
| "String: " + lcsvp.getValueByLabel("Charlie") | |
| ); | |
| } | |
| } | |
| /** | |
| * Get a LabeledCSVParser from a file | |
| * @param file file to be read | |
| * @return LabeledCSVParser | |
| * @throws IOException Unable to open file for parsing | |
| */ | |
| public static LabeledCSVParser getLabeledParser(File file) throws IOException { | |
| FileInputStream fis = new FileInputStream(file); | |
| InputStreamReader isr = new InputStreamReader(fis); | |
| CSVParser parser = new CSVParser(isr); | |
| LabeledCSVParser lcsvp = new LabeledCSVParser(parser); | |
| return lcsvp; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Alpha | Bravo | Charlie | |
|---|---|---|---|
| 12345 | $3.50 | Hello World | |
| 23456 | $4.50 | Hello Xord |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment