【问题标题】:BufferedReader to remembe line between functionsBufferedReader 记住函数之间的界限
【发布时间】:2015-03-25 13:16:44
【问题描述】:

抱歉,嗯.. 深奥的标题,但这是我的问题? 如果我在一个函数中有一个BufferedReader,我可以让它逐行读取,每次读取一行时,它都会读取上次读取的行之后的行,但考虑一下:

我有一个函数初始化BufferedReader,从文件中读取几行,然后将BufferedReader 传递给另一个函数,然后从同一个文件中读取几行。假设文件包含 10 行,第一个函数读取 6 行,第二个函数读取 4。

问题是当 BufferedReader 作为参数传递给第二个函数时,它是从文件的开头开始读取文件,还是从第一个函数中的BufferedReader 停止的位置开始。

BufferedReader br; //initialized somewhere
public void reada(){
    for(int I=0; I<6; I++){
        br.readLine();
    }
    //readb(br); Will calling this(and not the following line) read the first 4 or last 4 lines in a 10 line file?
    //readc(); Will calling this(and not the above line) read the first 4 or last 4 lines in the same file?
}

public void readb(BufferedReader reader){
    for(int j=0; j<4; j++){
        reader.readLine();
    }
}

public void readc(){
    for(int k=0; k<4; k++){
        br.readLine();
    }
}

【问题讨论】:

  • "The question is when the BufferedReader is passed as an argument to the second function, will it start reading the file from the beginning of the file, or will it start from where the BufferedReader left off in the first function." -- 这很容易测试,我建议你这样做:编写一个小程序并测试它。
  • 你尝试的时候发生了什么?你有什么理由相信它会神奇地倒回文件并重新开始,因为你将它传递给另一个方法?

标签: java file file-io io bufferedreader


【解决方案1】:

是的,如果 BufferedReader 没有关闭,它将从上次停止的地方读取。因为它们在同一个进程上下文中并且使用同一个文件处理程序,所以它们使用的是文件处理程序的相同“当前偏移量”。

【讨论】:

  • 没有“两者”之分。这里只有一个BufferedReader
【解决方案2】:

提供的两个示例都将从reada 停止的地方继续阅读。我相信,为了从头开始重新启动,必须​​调用close() 然后再次初始化它。或者只是使用另一个BufferedReader。我敢肯定还有其他方法,但这就是我想到的。

【讨论】:

  • '再次初始化'表示'另一个BufferedReader'。这不是两种不同的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 2016-08-26
相关资源
最近更新 更多