如何使用java计算csv中的总行数

时间:2013-08-02 05:34:14

标签: java

我有一个csv文件。我想用Java编写一个函数,它会告诉我csv中有多少行。有人可以帮助我实现这个目标。

csv具有以下格式:

"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

提前致谢

5 个答案:

答案 0 :(得分:4)

以下函数计算任何文件中的行数...

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

答案 1 :(得分:3)

试试这个,

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

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

答案 2 :(得分:2)

您可以计算行数并减去一行。计算你可以调用BufferedReader.readLine()的次数;你可能想忽略空行。

答案 3 :(得分:1)

使用正则表达式模式匹配换行符,并计算匹配项?

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

计数(换行符)将比有多少不同的行少一个。请注意,您的第一行是标题,而不是数据。

答案 4 :(得分:0)

如果您确定该字段未在多行中拆分,则可以读取由换行符分隔的每一行。 否则使用提到的here库之一。