java - Read one line at time from a file when a function is called each time -


string time=read_one_line();  public static string read_one_line() throws filenotfoundexception, ioexception {    fileinputstream fin=new fileinputstream("sample.txt");    bufferedreader br=new bufferedreader(new inputstreamreader(fin));    str=br.readline();    next_line=br.readline();    return next_line; } 

each time should read 1 line text file called "sample.txt" , return it. next time should return next line , on....

contents of sample.txt are:

date:0   year:0  hour:0  minute:0    seconds:0   milliseconds:310  date:0   year:0  hour:0  minute:0    seconds:0   milliseconds:0  date:0   year:0  hour:0  minute:0    seconds:0   milliseconds:10  date:0   year:0  hour:0  minute:0    seconds:0   milliseconds:0  date:0   year:0  hour:0  minute:0    seconds:0   milliseconds:380  date:0   year:0  hour:0  minute:0    seconds:10  milliseconds:-840  date:0   year:0  hour:0  minute:0    seconds:0   milliseconds:0  date:0   year:0  hour:0  minute:0    seconds:0   milliseconds:0  date:0   year:0  hour:0  minute:0    seconds:0   milliseconds:0  date:0   year:0  hour:0  minute:0    seconds:0   milliseconds:0 

but rather reading , returning first line each time.. please tell me how increment next line , return when call function next time.

you creating new fileinputstream each time function called. therefore, file read beginning each time.

create bufferedreader once, outside of function , pass in on each call, file successively read.

public static string read_one_line(final bufferedreader br) throws ioexception {   next_line=br.readline();    return next_line; } 

usage like

static void main(string args[]) throws ioexception {    fileinputstream fin=new fileinputstream("sample.txt");    try {      bufferedreader br=new bufferedreader(new inputstreamreader(fin));      string line = read_one_line(br);     while ( line != null ) {       system.out.println(line);       line = read_one_line(br);     }    } {     fin.close(); // make sure close file when we're done.   } } 

note in case, read_one_line omitted , replaced simple br.readline().

if want every other line, can read 2 lines in each iteration, like

string line = read_one_line(br); while ( line != null ) {   system.out.println(line);   string dummy = read_one_line(br);   line = read_one_line(br); } 

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -