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

public void seek(long pos) throws IOException

1
2
3
4
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 。25054E5D09B52E37445E78BAC638CCF1E0CDE19F02236_500_132.jpg

90405B094B3802216CA0A3382AD6496A9D97B133C33E8_500_146.jpg

DD71A083C7DE6E9A36CBB82C8E694FDE829654C0828BB_500_145.jpg


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

public abstract FileChannel position(long newPosition) throws IOException

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

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

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

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

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