我从一个简单的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());
}
}发布于 2015-03-10 16:39:37
你要给readLine()打两次电话
while (t.readLine()!=null) {
System.out.println(t.readLine());
}相反,预先计算readLine();
String tmp;
while((tmp = t.readLine()) != null) {
System.out.println(tmp);
}发布于 2015-03-10 16:51:56
试试这个:
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}每次调用readlin()时,它都会转到下一行,这就是为什么只打印行的原因。
发布于 2017-10-31 13:27:14
在使用RandomAccessFile时,您也可以在任何搜索位置读取,而不是逐行读取以获得优化的I/O性能。
RandomAccessFile raf = new RandomAccessFile("file","r");
raf.seek(info.getStartingIndex());//Maintain info while serializing obj
byte[] bytes = new byte[info.getRecordLength()];//length stored earlier similarly
raf.read(bytes);
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();https://stackoverflow.com/questions/28969258
复制相似问题