简体   繁体   中英

Reading data from a csv file Java

I want to read data from my dataset train.csv and I am trying to implement that using Java. My aim is to get this raw data in order to in the csv file in order to create a decision tree from this database. I have class DAO in which I implemented a method called extractTrainingData where I am writing the codes to read the data. This method is as follow.

public static BufferedReader exTractTraningData(File datafile, String ListOfCharacteristics) throws IOException {

    try {
        //create BufferedReader to read csv file
        BufferedReader reader = new BufferedReader(new FileReader(datafile));

        String strLine = "";
        StringTokenizer st = null;

        int lineNumber = 0, tokenNumber = 0;;

        String line = reader.readLine();

        while ((strLine = line) != null) {
            lineNumber++;
            //break comma separated line using ","
            st = new StringTokenizer(strLine, ",");

            while (st.hasMoreTokens()) {
                //display csv values
                tokenNumber++;
                System.out.println("Line # " + lineNumber
                        + ", Token # " + tokenNumber
                        + ", Token : " + st.nextToken()
                         + ": " + line);
            }
            //reset token number
            tokenNumber = 0;;
        }
    } catch (Exception e) {

        System.out.println("Exception while reading csv file: " + e);
    }
    return null;
}

When I run the main class, it repeats the row repeatedly. I don't really know if I am doing it correctly. I tried to follow an online tutorial. Can anyone help me out? Thank you

The problem is that your read call is outside of the while loop's test.

String strLine = "";

String line = reader.readLine();

while ((strLine = line) != null) {

Should probably be

String strLine = "";

while ((strLine = reader.readLine()) != null) {

So that each iteration of the while loop operates on the result of a new read attempt

Your while loop never updates because you never update line .

What you probably want is

String strLine;
while ((strLine = reader.readLine()) != null) {
    ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM