Question

I have a csv file. I want to write a function in Java which will tell me how many rows are there in csv. Could someone please help me in achieving this.

csv has following format:

"Time","Actual","Time","Expected","Time","Status"
"2012-09-01 00:00:00",580.543,"2012-09-01 00:00:00",570.761,"2012-09-01 01:00:00",0
"2012-09-01 01:00:00",646.703,"2012-09-01 01:00:00",672.926,"2012-09-01 02:00:00",0
"2012-09-01 02:00:00",680.705,"2012-09-01 02:00:00",687.784,"2012-09-01 03:00:00",0
"2012-09-01 03:00:00",661.968,"2012-09-01 03:00:00",702.436,"2012-09-01 04:00:00",0
Was it helpful?

Solution

following function counts the number of line in any file...

public int count(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
    byte[] c = new byte[1024];
    int count = 0;
    int readChars = 0;
    boolean empty = true;
    while ((readChars = is.read(c)) != -1) {
        empty = false;
        for (int i = 0; i < readChars; ++i) {
            if (c[i] == '\n') {
                ++count;
            }
        }
    }
    return (count == 0 && !empty) ? 1 : count;
    } finally {
    is.close();
   }
}

OTHER TIPS

Try this,

BufferedReader bufferedReader = new BufferedReader(new FileReader(FILENAME));
     String input;
     int count = 0;
     while((input = bufferedReader.readLine()) != null)
     {
         count++;
     }

     System.out.println("Count : "+count);

You can count the number of lines and subtract one. Count how many times you can call BufferedReader.readLine(); You might want to ignore empty lines.

Use a regex Pattern to match newline, and count the matches?

Pattern patt = Pattern.compile("\\n");
Matcher m = patt.matcher( text);
//
int newlines = 0;
while (m.find()) {
    newlines++;
}

Count(newlines) will be one less than how many distinct lines there are. Note that your first line is headers, not data.

You can just read every single line separated by newline if you are sure that field are not splitted in multiple lines. Else use one of the library mentioned here.

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