-1

我有一个 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
4

5 回答 5

8

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

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();
   }
}
于 2013-08-02T05:38:27.430 回答
3

尝试这个,

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

     System.out.println("Count : "+count);
于 2013-08-02T05:38:23.727 回答
2

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

于 2013-08-02T05:36:42.463 回答
1

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

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

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

于 2013-08-02T05:35:25.457 回答
0

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

于 2013-08-02T05:37:11.527 回答