Java.io.RandomAccessFile.seek() 方法
描述
java.io.RandomAccessFile.seek(long pos) 方法设置文件指针偏移量,从该文件的开头开始测量,下一次读取或写入发生在该位置。 偏移量可以设置在文件末尾之外。 设置超出文件末尾的偏移量不会更改文件长度。 只有在将偏移量设置到文件末尾之后,文件长度才会改变。
声明
以下是 java.io.RandomAccessFile.seek() 方法的声明。
public void seek(long pos)
参数
pos − 偏移位置,以从文件开头开始的字节为单位,设置文件指针的位置。
返回值
此方法不返回值。
异常
IOException − 如果 pos 小于 0 或发生 I/O 错误。
示例
下面的例子展示了 java.io.RandomAccessFile.readUTF() 方法的使用。
package com.tutorialspoint;
import java.io.*;
public class RandomAccessFileDemo {
public static void main(String[] args) {
try {
// create a new RandomAccessFile with filename test
RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");
// write something in the file
raf.writeUTF("Hello World");
// set the file pointer at 0 position
raf.seek(0);
// print the string
System.out.println("" + raf.readUTF());
// set the file pointer at 5 position
raf.seek(5);
// write something in the file
raf.writeUTF("This is an example");
// set the file pointer at 0 position
raf.seek(0);
// print the string
System.out.println("" + raf.readUTF());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
假设我们有一个文本文件c:/test.txt,其内容如下。 该文件将用作我们示例程序的输入 −
ABCDE
让我们编译并运行上面的程序,这将产生下面的结果 −
Hello World Hel This i

