0

So, I'm using OpenCSV for a project I'm working on, and I've been doing fine so far, I managed to read a CSV file, as well as write to one. Because it's my first time using OpenCSV, I decided to use a tutorial I found on the internet, and adapt it a bit. So, what I've done is made a method called ReadData(). I can read the CSV and print it to the console fine, but what I want to do is access the "nextLine" array outside of the method.

    public void ReadData(String filelocation) {
    filelocation = System.getProperty("user.dir")+"/data/"+filelocation;
    try {
        CSVReader savereader = new CSVReader(new FileReader(filelocation), ',', '"', 0);
        String[] nextLine;
            while((nextLine = savereader.readNext()) != null) {
                if(nextLine != null) {
                    //Make sure everything went through
                    System.out.println("Data Read. Results:");
                    System.out.println(Arrays.toString(nextLine));
                }
            }
    } catch (FileNotFoundException ex) {
        //Handle Exception
    } catch (IOException ex) {
        //Handle Exception
    }
}

This method reads the data from a file I specify. But, I want to be able to do things with that data. For example, I would want to take nextLine[0], and see if it is empty, if it is, do one thing. If it's not, then I want to do something else that would make it equal something.

Thanks in advance, and I hope I was clear enough about what I'm trying to accomplish!

Regards,

Johnny

1 Answers1

0

The problem you have is an java issue not opencsv. The problem is that nextline is local to the method - in your case local to the try block. So anything outside of the method cannot reference nextline.

You could make nextline local to the method instead of the try and have the method return nextline (change from void to String[]) but you would only be returning the last line.

For what you want (to be able to check all the data after it has been read) is to store each String[] you read into a List and have the method return that. But if you are going to do that you should just use the readAll method of CSVReader (http://opencsv.sourceforge.net/apidocs/index.html). Be warned though that if you do that you are risking an OutOfMemoryException when dealing with large files.

Hope that helps.

Scott Conway
  • 975
  • 7
  • 13