java读取linux文件_Java文件定位读取

1. 使用RandomAccessFile对象的seek函数来实现

public void seek(long pos) throws IOException

RandomAccessFile randomAccessFile = newRandomAccessFile ("./chanel.txt", "r"); // Set the file position 离文件起始位置10字节处randomAccessFile.seek (10);System.out.println(randomAccessFile.readLine());

其中 pos 代表偏移量,pos = 0, 代表 文件起始位置,pos = 10 表示偏移文件起始位置的10个字节处。注意是字节为单位。一个ASCII 码的代表一个字节,如'A' , 'a'。汉字代表两个字节。

以下图片是EditPlus,指示的,我理解一个字节占一个col 。

f60ebf7461d2cfa71442d5eb187c379f.png

cf1eb1e6aa46ed017058f65757ad5881.png

35ec7848217578aff087f9427afbfad6.png

2. 使用FileChannel的position方法来实现

public abstract FileChannel position(long newPosition) throws IOException

其中newPosition与上面的pos含义一样。

在使用FileChannel之前,必须先打开它。但是,我们无法直接打开一个FileChannel,

需要通过使用一个InputStream、OutputStream或RandomAccessFile来

获取一个FileChannel实例。下面是通过RandomAccessFile打开FileChannel的示例

RandomAccessFile randomAccessFile = newRandomAccessFile ("./chanel.txt", "r"); FileChannel fileChannel = randomAccessFile.getChannel( );//Set the file position离文件起始位置10字节处 fileChannel.position (10);System.out.println(randomAccessFile.readLine());

推荐阅读:

0b1331709591d260c1c78e86d0c51c18.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值