eggman
eggman

Reputation: 423

Using a loop I want to find the value of a column from my CSV file java

Forgive me if this is a basic (or not very well explained) question, I am fairly new to Java and have been reading extensive material as well as trying to understand the relevant Javadoc but to no avail.

To give a brief background as to what I am trying to create, I have created a reader class which reads data in from a csv file (4 lines long) including fields such as Item ID, price, description etc. I have created a separate demo class that displays the details of this csv file (through creating an instance of my reader class) and am now trying to create a method that asks the user to input an Item ID that then displays the corresponding Item, based on the ID input by the user. The part I am stuck on is accessing specific rows/columns in a csv file and then comparing these with a given string (entered by the user which corresponds to a specific field in the csv file)

This is what I have come up with thus far:

input = new Scanner(System.in);
    System.out.println("Enter a product code");
    String prodC = input.next();
    //Here I want to know if there is a way of accessing a field in a csv file

Any ideas would be greatly appreciated.

UPDATE

Thank you for quick responses, am currently reading through and seeing how I can try to implement the various techniques. In response to the comment asking about the file reader, this is how I have set that out:

 public CatalogueReader(String filename) throws FileNotFoundException {
    this.filename = filename;
    this.catalogue = new Catalogue();

    Scanner csvFile;
    try {
        csvFile = new Scanner(new File(filename));
    } catch (FileNotFoundException fnf) {
        throw new FileNotFoundException("File has not been found!");
    }
    csvFile.useDelimiter("\n");
    boolean first = true;
    String productCode;
    double price;
    String description;
    double weight;
    int rating;
    String category;
    boolean ageRestriction;
    String csvRows;
    while (csvFile.hasNextLine()) {
        csvRows = csvFile.nextLine();
        if (first) {
            first = false;
            continue;
        }
        System.out.println(csvRows);
        String[] fields = csvRows.split(",");
        productCode = (fields[0].trim());
        price = Double.parseDouble(fields[1].trim());
        description = fields[2].trim();
        weight = Double.parseDouble(fields[3].trim());
        rating = Integer.parseInt(fields[4].trim());
        category = fields[5].trim();
        ageRestriction = Boolean.parseBoolean(fields[6].trim());
        catalogue.addAProduct(new Item(productCode, price, description, weight, rating, category, ageRestriction));             
    }
    csvFile.close();
}

}

Upvotes: 1

Views: 5029

Answers (3)

karim
karim

Reputation: 15589

You can create an array list of object. An object for each line in the CSV. Then search the array object with your search criteria.

User CSVReader framework to read the csv file. Sample code (not exactly what you want)

 FileInputStream fis = new FileInputStream(file);
            CSVReader reader = new CSVReader(new BufferedReader( new InputStreamReader(fis, "UTF-8" )));

            ArrayList<String> row = new ArrayList<String>();
            ArrayList<Entry> entries = new ArrayList<Entry>();
            // a line = ID, Name, Price, Description
            while (!reader.isEOF()) {
                reader.readFields(row);
                if( row.size() >= 4)
                    entries.add(new Entry(row.get(0), row.get(1), row.get(2), row.get(3)));
            }
            System.out.println("Size : "+entries);

Upvotes: 0

Tim B
Tim B

Reputation: 41208

If you are just doing a single look-up and then exiting then just remember the String you are looking for. As you parse the lines compare to see if you have a match and if you do then return that line.

For repeated searches that would be very inefficient though. Assuming your data set is not too large for memory you would be better off parsing the file and putting it into a Map:

Map<String, Data> dataMap = new HashMap<>();

Parse the file, putting all the lines into the map

Then the lookup just becomes:

 Data d = dataMap.get(lineKey);

If d is null then there is no matching line. If it not null then you have found your line.

Upvotes: 0

Matt617
Matt617

Reputation: 458

ok so for a CSV file like this:

"1.0.0.0","1.0.0.255","16777216","16777471","AU","Australia"
"1.0.1.0","1.0.3.255","16777472","16778239","CN","China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"
"1.0.32.0","1.0.63.255","16785408","16793599","CN","China"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japan"
"1.0.128.0","1.0.255.255","16809984","16842751","TH","Thailand"

here is a sample of how to read using Java Native Libraries

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class CSVReader {

  public static void main(String[] args) {

    CSVReader obj = new CSVReader();
    obj.run();

  }

  public void run() {

    String csvFile = YOURFILEPATHHERE ;
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";

    try {

        br = new BufferedReader(new FileReader(csvFile));
        while ((line = br.readLine()) != null) {

                // use comma as separator
            String[] country = line.split(cvsSplitBy);

            System.out.println("Country [code= " + country[4] 
                                 + " , name=" + country[5] + "]");

        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    System.out.println("Done");
  }

}

does this help?

Upvotes: 1

Related Questions