What function should i use for Java programming to get the total number of colons in a CSV file?
PS: not a Java developer.
What function should i use for Java programming to get the total number of colons in a CSV file?
PS: not a Java developer.
Read the file char by char (using a BufferedReader to make it fast), and count each colon you meet:
int countColons() throws IOException {
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file.txt), "UTF-8"))) {
int count = 0;
int c;
while ((c = in.read()) >= 0) {
if (c == ':') {
count++;
}
}
return count;
}
}
Of course, you should use the appropriate encoding for your file. Not necessarily UTF-8.
Read the file line by line. For every line, use replaceAll
to get rid of every character that isn't a colon. Then get the length of the resulting String
. Keep a cumulative total of the results of this.
If you don't want to reinvent the wheel:
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
int count = StringUtils.countMatches(FileUtils.readFileToString(new File("file.csv")), ":");
One cool trick I found a while ago for counting the number of occurences is to take the length of the string
, and minute all the values from it that are not your desired value.
Example
// Assume fileStr contains everything in the file
int numberOfColons = fileStr.length() - fileStr.replaceAll(":", "").length();
This will give you the number of colons in the file.
Edit
Just remembered when I got it from. It is from this question.
The reason why I like this approach
Obviously, it's extremely short, which is always nice. It does give some of a hit to the processor, but it avoids all loops (in your code at least) and it seems like a very elegant solution to the problem.