Read one line at time from a file when a function

2019-09-09 15:59发布

问题:

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);
}