Android/Java - Random Read line not changing -
my text file contains known number of lines (the first line of file number of lines). want randomly read line file - use linenumberreader
. problem is, doesn't generate new string - random number changes string gets linenumberreader
doesn't.
as title implies android app. textbox
output area, testbox
debugging (in code displays random number - check has changed) , r
random
this sample code onclick
button in app.
string filename = "\\sdcard\\q's.txt"; try { bufferedreader br = new bufferedreader( new inputstreamreader( new datainputstream( new fileinputstream(filename)))); // number of lines in text file numlines = integer.parseint(br.readline().tostring().trim()); // random number , write test text box int rnd = r.nextint(numlines); string tmp = integer.tostring(rnd); testbox.settext(tmp); // random number - go line - save in string "text" linenumberreader rdr = new linenumberreader(br); rdr.setlinenumber(r.nextint(numlines)); textbox.settext(rdr.readline()); } catch (filenotfoundexception e) { textbox.settext("filenotfound"); e.printstacktrace(); } catch (ioexception e) { textbox.settext("ioexception"); e.printstacktrace(); } catch (numberformatexception nfe){ textbox.settext("number formated wrong"); } {}
what doing wrong? have tried closing , reseting br
, rdr
and can't seem work.
the line number doesn't affect line gets returned, line number reported it.
the whole point of linenumberreader
not automatically seek specific line, it's keep track of current line number without having worry it.
in other words, open reader , start reading. when find line of interest, can call getlinenumber()
find out line was.
to end, setlinenumber()
changes reported line number current line. not move file pointer line in file.
to specific line rnd
, simplest solution read rnd
lines in loop. last 1 read 1 want. in pseudo-code:
open bufferedreader br limit first line of br set rnd number 1 limit while limit > 0: set line next line of br decrement limit use line
if, or when, turns out inefficient you, can start thinking pre-loading data memory structure of sort.
Comments
Post a Comment