Java iteration reading & parsing
Posted
by
Patrick Lorio
on Stack Overflow
See other posts from Stack Overflow
or by Patrick Lorio
Published on 2012-06-30T21:12:24Z
Indexed on
2012/06/30
21:15 UTC
Read the original article
Hit count: 274
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?
© Stack Overflow or respective owner