【发布时间】:2015-03-10 16:37:13
【问题描述】:
我正在从一个简单的 RandomAccessFile 中读取 10 行并打印每一行。文本文件中的具体行如下:
蓝色
绿色
气泡
奶酪
百吉饼
拉链
糖果
鲸鱼
猴子
图表
当我逐行阅读时按顺序打印它们时,我的输出是这样的:
绿色
奶酪
拉链
鲸鱼
图表
我不明白为什么我的方法会跳过文件中的每一行。我是否误解了 RandomAccessFile 的工作原理?我的方法如下:
RandomAccessFile file = new RandomAccessFile(FILEPATH, "rw");
read(file);
public static void read(RandomAccessFile t) throws IOException{
while (t.readLine()!=null) {
System.out.println(t.readLine());
}
}
【问题讨论】:
-
当你使用 readLine 时,文件中的指针会跳转到下一个位置,所以当你使用它两次时,一次在 while 中,在 print 中,你在 while 和 print 之后跳转第二个值。
标签: java randomaccessfile