Java RandomAccessFile getFilePointer()方法

java.io.RandomAccessFile.getFilePointer() 方法返回当前在此文件中的偏移。

1 语法

public long getFilePointer()

2 参数

3 返回值

此方法返回从文件开始的偏移量,以字节为单位,进行下一个读或写操作发生。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.RandomAccessFile.getFilePointer()方法的例子
 */
import java.io.*;

public class Demo {
    public static void main(String[] args) {

        try {
            // create a new RandomAccessFile with filename Example
            RandomAccessFile raf = new RandomAccessFile("d:/test.txt", "rw");

            // write something in the file
            raf.writeUTF("Hello World");

            // set the file pointer at 0 position
            raf.seek(0);

            // read and print the contents of the file
            System.out.println("" + raf.readUTF());

            // return the file pointer
            System.out.println("" + raf.getFilePointer());

            // change the position of the file pointer
            raf.seek(5);

            // return the file pointer
            System.out.println("" + raf.getFilePointer());

            // close the strea and release resources
            raf.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

输出结果为:

Hello World
13
5

热门文章

优秀文章