Question

What I am trying to do: Using OpenCSV, Write a method that will allow me to get information from a particular column in a CSV. This CSV will (in practice) only have two rows: A header row, and one row of information. I need to take certain bits and manipulate them to put them into another CSV (but haven't gotten that far).

The problem: Each time I call this method, it moves down a row. Example: I search for the Product ID, and it returns the Product ID on row 2, which is good. Then I run it again and search for the Description, and it returns the Description on row 3. Not good. Run it again, and it finds the correct column on row 4. Again, not good. It will only ever need to look on row 2. I feel like the answer is very simple, but I'm not seeing it.

public class Application {

    public static String ItemNabber(String item, CSVReader reader, String [] headerLine) throws IOException {
        String passedItem = null;

        try {

                for (int i = 0; i < headerLine.length; i++){
                    if (headerLine[i].equals(item)) //customize name
                    {
                        String [] itemFound = reader.readNext();
                        System.out.println(itemFound[i]);
                        passedItem = itemFound[i];
                        itemFound = null;



                    }

        }

            } 
        catch (FileNotFoundException e) 
            {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
            return passedItem;
    }

    public static void main(String[] args) throws IOException {
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter myFilter = new FileNameExtensionFilter("Text Files", "txt", "csv");
        chooser.setFileFilter(myFilter);
        int returnVal = chooser.showOpenDialog(null);
            if(returnVal == JFileChooser.APPROVE_OPTION) 
            {
           System.out.println("You chose to open this file: " +
                chooser.getSelectedFile().getAbsolutePath());
            }
            String filePath = String.format(chooser.getSelectedFile().getAbsolutePath());

            CSVReader reader = new CSVReader(new FileReader(filePath), '|');

            String [] headerLine = reader.readNext(); 
            ItemNabber("PRODID", reader, headerLine);
            ItemNabber("DESCR", reader, headerLine);

In this example, it finds the correct PRODID, but scoots down a row to find the Description.

Thanks in advance!

Was it helpful?

Solution

You call reader.readNext in the function.

String [] itemFound = reader.readNext();

Just read the line you want as pass it as a string argument:

String [] headerLine = reader.readNext(); String [] dataLine = reader.readNext();

ItemNabber("PRODID", dataLine, headerLine); ItemNabber("DESCR", dataLine, headerLine);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top