Java iteration reading & parsing
- by Patrick Lorio
I have a log file that I am reading to a string
public static String Read (String path) throws IOException {
StringBuilder sb = new StringBuilder();
InputStream in = new BufferedInputStream(new FileInputStream(path));
int r;
while ((r = in.read()) != -1) {
sb.append(r);
}
return sb.toString();
}
Then I have a parser that iterates over the entire string once
void Parse () {
String con = Read("log.txt");
for (int i = 0; i < con.length; i++) {
/* parsing action */
}
}
This is hugely a waste of cpu cycles. I loop over all the content in Read. Then I loop over all the content in Parse. I could just place the /* parsing action */ under the while loop in the Read method, which would be find but I don't want to copy the same code all over the place.
How can I parse the file in one iteration over the contents and still have separate methods for parsing and reading?
In C# I understand there is some sort of yield return thing, but I'm locked with Java.
What are my options in Java?