|
| 1 | +//Basic Reading and printing of CSV File consiting data related to fruits etc |
| 2 | +//NOTE : Take care of the file and package name and make sure the csv file location is set |
| 3 | +//Coder : Phantom-fs |
| 4 | + |
| 5 | +package FruitCSV; |
| 6 | + |
| 7 | +//This is an external library, use steps in CSV README.md file to know how to add it |
| 8 | +import org.apache.commons.csv.*; |
| 9 | +import java.io.*; |
| 10 | + |
| 11 | +public class FruitCSVReading |
| 12 | +{ |
| 13 | + static String newline = System.getProperty("line.separator"); |
| 14 | + public void readCSV () |
| 15 | + { |
| 16 | + try |
| 17 | + { |
| 18 | + //change location to the directory where .csv file is saved |
| 19 | + FileReader fileReader = new FileReader("B:\\3- Java Programs\\IdeaProjects\\CSVData\\CSV Files\\SimpleFruitData.csv"); |
| 20 | + CSVParser csvParser = new CSVParser(fileReader, CSVFormat.DEFAULT); |
| 21 | + |
| 22 | + Styling.lineTitle("Fruit Data:"); |
| 23 | + |
| 24 | + for (CSVRecord csvRecord : csvParser) |
| 25 | + { |
| 26 | + Styling.color("Record No - " + csvRecord.getRecordNumber() + newline, "red"); |
| 27 | + Styling.color("Fruit - " + csvRecord.get(0), "yellow"); |
| 28 | + Styling.color("Price - " + csvRecord.get(2), "purple"); |
| 29 | + Styling.color("Quantity Available - " + csvRecord.get(1), "blue"); |
| 30 | + Styling.color("Rating - " + csvRecord.get(3), "cyan"); |
| 31 | + Styling.color(newline + "Comments - " + csvRecord.get(4), "green"); |
| 32 | + Styling.line(); |
| 33 | + } |
| 34 | + |
| 35 | + csvParser.close(); |
| 36 | + } |
| 37 | + catch (FileNotFoundException e) |
| 38 | + { |
| 39 | + System.out.println("File not found"); |
| 40 | + } |
| 41 | + catch (IOException e) |
| 42 | + { |
| 43 | + throw new RuntimeException(e); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + public static void main (String[] args) |
| 48 | + { |
| 49 | + FruitCSVReading csvBasicReading = new FruitCSVReading(); |
| 50 | + csvBasicReading.readCSV(); |
| 51 | + } |
| 52 | +} |
0 commit comments