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
而是每次只读它并返回第一行..请告诉我如何递增到下一行并在下次调用此函数时返回它。
答案 0 :(得分:3)
每次调用函数时,您都在创建一个新的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);
}