java - Android - More efficient method to read a big text file -
i've big txt file (1.5 mb) private resource in android application.
file structured this:
"a1|a2|a3|a4#b1|b2|b3|b4#c1|c2|c3|c4#..."
where a1, a2, a3, b1... alphanumerical strings. need create object each group of strings, this:
myobject obja = new myobject("a1", "a2", "a3", "a4"); myobject objb = new myobject("b1", "b2", "b3", "b4"); ...
i've developed reader class in order read file... looks bit slow.
here is:
public class textfilereader { private static charset charset = charset.defaultcharset(); private inputstream stream; private inputstreamreader reader; private stringbuffer buffer; public textfilereader(context c, string s) { try { this.stream = c.openfileinput(s); this.reader = new inputstreamreader(this.stream, charset); this.buffer = new stringbuffer(); } catch (filenotfoundexception e) { } } public string readnextsubstring(char div) throws ioexception { buffer.delete(0, buffer.length()); int i; char c; while ((i = reader.read()) > -1) { c = (char) i; if (c == div) break; buffer.append(c); } return buffer.tostring(); } }
i use textfilereader in way:
textfilereader reader = new textfilereader(context, "big_file.txt"); //first group string group = reader.readnextsubstring('#'); string[] info = group.split("\\|"); myobject obja = new myobject(info[0], info[1], info[2], info[3]); //second group group = reader.readnextsubstring('#'); info = group.split("\\|"); myobject objb = new myobject(info[0], info[1], info[2], info[3]); //obviously done in while loop :) ...
what think method? structured in more efficient way?
don't care space, care time (the emulator takes lot of time in order read file)
i can find 1 simple tweak can speed improving how time spend on doing this: group.split("\\|");
the way java each time run line, compile new regex.
if this:
pattern pattern = pattern.compile("\\|"); textfilereader reader = new textfilereader(context, "big_file.txt"); while (reader.hasmoredata) { string group = reader.readnextsubstring('#'); string[] info = pattern.split(group); myobject obja = new myobject(info[0], info[1], info[2], info[3]); ... } this reduce time takes compile pattern - can quite considerable amount of data.
also, 1.5mb not much, perhaps loading memory using bufferedreader improve performance more.
Comments
Post a Comment