How do I use a CSV file as a database with Java?

Viewed 1632

I'm working my way on learning Java and I would like to know how to parse a CSV file properly.

Let's say I have a store. I created a CSV file the looks like this:

enter image description here

To my main class I added a customer instance that can buy items. Currently it doesn't do anything, but I'd like that action to search the CSV file and if it finds that product in the list, then it would update that product's quantity accordingly. Right now, it doesn't do anything:

public class Customer {
    int custID;
    String firstName;
    String lastName;

    public void buyProd(){
        Scanner sc = new Scanner(System.in);
        System.out.println("To buy a product, enter it's name:");
        String prodToBuy = sc.nextLine();
        System.out.println("You bought " + prodToBuy + " \nThanks for buying");
    }

    public void returnProd(){
        System.out.println("Thanks for returning the product");
    }
}

I found a piece of code that can parse through all of the CSV file, but I'm not sure how I'm supposed to stop on that keyword of the product, then retrieve and update the quantity field


public class CSVParser{
    public static void main(String[] args) {
        try {
            String fileName= "C:\\temp\\test.csv";
            File file= new File(fileName);
            Scanner scanner = new Scanner(file);
            // set comma as delimiter
            scanner.useDelimiter(",");
            // read all fields
            while (scanner.hasNext()) {
                System.out.print(scanner.next() + " ");
            }
            scanner.close();

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
    }
}

I know that I'm not supposed to use a CSV file as a database. I'm not going to, this is just an assignment that I'd like to understand. My CSV files will not contain more than a couple of rows and columns at best.

Any help on the matter would be great.

0 Answers
Related