使用RandomAccessFile到达文件中的特定行 [英] Reaching a specific line in a file using RandomAccessFile

查看:518
本文介绍了使用RandomAccessFile到达文件中的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过RandomAccessFile将光标定位到文件中特定行的开头?

Is it possible to position cursor to the start of a specific line in a file through RandomAccessFile?

例如我想在文件中第111行的char 10到20之间更改String。该文件具有固定长度记录。

For e.g. I want to change String starting at char 10 till 20 in line 111 in a file. The file has fixed length records.

是否可以使用RandomAccessFile将光标直接定位到第111行的开头?

Is it possible to directly position the cursor to start of line 111 using RandomAccessFile ?

更新:

我使用了以下代码。但是,它返回null。

I used the following code. However, its returning null.

行长度为200个字符(如果我没有错,则为200字节)

Line length is 200 characters (which is 200 bytes if I am not wrong)

File f = new File(myFile); 
RandomAccessFile r = new RandomAccessFile(f,"rw"); 
r.skipBytes(200 * 99);   // linesize * (lineNum - 1) 
System.out.println(r.readLine());

我哪里错了?

推荐答案

我不确定但似乎RandomAccessFile不支持这样的功能。
由于RAF以字节运行,我们可以跳过特定的字节数,如果你的文件有固定的行宽,这可以通过

I'm not sure but seems RandomAccessFile do not support such functionality. As RAF operates with bytes we can skip specific amount of bytes, and if your file has fixed line width this can be achieved by

file.skipBytes(110 * lineSizeInBytes);

否则,你需要这样的东西:

Otherwise, you need something like this:

for (int i = 0; i < 110; i++) file.readLine();
String line = file.readLine();

这篇关于使用RandomAccessFile到达文件中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆