Search code examples
javaopencsv

how to count total rows in csv using java


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

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();
       }
    }