如何使用java计算csv中的总行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18009416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to count total rows in csv using java
提问by Deepak Shah
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 文件。我想用 Java 编写一个函数,它会告诉我 csv 中有多少行。有人可以帮助我实现这一目标。
csv has following format:
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
Thanks in advance
提前致谢
采纳答案by Sukhdevsinh Zala
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();
}
}
回答by Thomas W
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.
Count(newlines) 将比有多少不同的行少一。请注意,您的第一行是标题,而不是数据。
回答by Peter Lawrey
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.
您可以计算行数并减去一。计算您可以调用 BufferedReader.readLine() 的次数;您可能想忽略空行。
回答by Luca Basso Ricci
回答by newuser
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);