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

拥有回忆 提交于 2019-12-13 04:35:42

问题


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 it should read one line from text file called "sample.txt" and return it. next time it should return next line and so 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 its reading and returning first line only each time.. please tell me how to increment to next line and return it when i call this function next time.


回答1:


You are creating a new FileInputStream each time the function is called. Therefore, the file is read from the beginning each time.

Create the BufferedReader only once, outside of the function and pass it in on each call, so that the file is successively read.

public static String Read_one_Line(final BufferedReader br) throws IOException
{
  next_line=br.readLine();

  return next_line;
}

usage would be 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);
    }

  } finally {
    fin.close(); // Make sure we close the file when we're done.
  }
}

Note that in this case, Read_one_Line could just be omitted and replaced by a simple br.readLine().

If you only want every other line, you can just read two 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);
}


来源:https://stackoverflow.com/questions/23059122/read-one-line-at-time-from-a-file-when-a-function-is-called-each-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!