【问题标题】:Read one line at time from a file when a function is called each time每次调用函数时从文件中读取一行
【发布时间】:2014-04-14 11:39:04
【问题描述】:
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;
}

每次它应该从名为 "sample.txt" 的文本文件中读取一行返回。下次它应该返回下一行等等......

sample.txt 的内容为:

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

而是每次只读取和返回第一行..请告诉我如何递增到下一行并在我下次调用此函数时返回它。

【问题讨论】:

  • 请不要将您的问题更改为全新的问题。这使得答案与问题不匹配,以后阅读此问题+答案的人只会感到困惑。如果您有新问题,请创建一个新问题。

标签: java file-io bufferedreader fileinputstream


【解决方案1】:

每次调用该函数时,您都会创建一个新的FileInputStream。因此,每次都从头开始读取文件。

在函数外部只创建一次BufferedReader,并在每次调用时将其传入,以便连续读取文件。

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

  return next_line;
}

用法会是这样的

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.
  }
}

请注意,在这种情况下,Read_one_Line 可以省略并替换为简单的br.readLine()

如果你只想要每隔一行,你可以在每次迭代中读取两行,比如

String line = Read_one_Line(br);
while ( line != null ) {
  System.out.println(line);
  String dummy = Read_one_Line(br);
  line = Read_one_Line(br);
}

【讨论】:

  • 谢谢你..辛苦了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-05
  • 1970-01-01
  • 2018-04-29
  • 2015-12-17
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
相关资源
最近更新 更多