java file seek_Java RandomAccessFile seek()方法
Java RandomAccessFile seek()方法
java.io.RandomAccessFile.seek(long pos)?方法將文件指針偏移量,從這個文件開始測量,進(jìn)行下一個讀或?qū)懖僮鳌F屏靠梢员辉O(shè)置為超出文件的末尾。設(shè)置偏移超出了文件的末尾不會改變文件長度。文件長度,也只是由偏移已被設(shè)置為超出文件的末尾之后寫入更改。
1 語法
public void seek(long pos)
2 參數(shù)
pos:偏移位置,以字節(jié)為單位從文件的開頭計量,在其上設(shè)置文件指針。
3 返回值
無
4 示例
package com.yiidian;
/**
* 一點教程網(wǎng): http://www.yiidian.com
*/
/**
* java.io.RandomAccessFile.seek(long pos)方法的例子
*/
import java.io.*;
public class Demo {
public static void main(String[] args) {
try {
// create a new RandomAccessFile with filename test
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);
// 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();
}
}
}
假設(shè)test.txt文件內(nèi)容如下:
ABCDE
輸出結(jié)果為:
Hello World
Hel This i
總結(jié)
以上是生活随笔為你收集整理的java file seek_Java RandomAccessFile seek()方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DT时代,企业打造数据中台的三大原则
- 下一篇: 双机高速互联