Re: Speeding up reading from files
Mark wrote:
I am using a BufferedReader to read character data in from a file. It
works but it's incredibly slow. (The file consists of a number of
separate messages, each separated by a special character. Each
message must be read into a separate string.)
Aside from the good answers others have provided, some additional side
remarks:
I use the following code (exception handling removed for brevity):
Most of the example removed for too much brevity.
String text = new String("");
Why not 'text = ""'?
BufferedReader in = null;
Why in the world would you assign to 'null' first, then discard that
initialization immediately?
in = new BufferedReader(new InputStreamReader(n=
ew
FileInputStream(_msgFile)));
int c;
Put 'c' in the loop body; its scope is too wide here. Actually,
follow others' advice here and don't read the input character by
character but buffer by buffer, as Roedy said.
while ((c = in.read()) != -1) {
if (c == '@') {
_msgList.add(text);
We'll assume an appropriate definition for '_msgList', but notice that
the variable name violates the Java coding conventions.
text = "";
} else {
text += (char)c;
Yes, Roedy's advice to use 'StringBuilder' will speed this up
considerably, and save heap memory.
}
}
if (text.length() > 0) {
_msgList.add(text);
}
<http://sscce.org/>
--
Lew