輸入流FileInputStream和輸出流 FileOutputStream,實現的是對磁盤文件的順序讀寫,而且讀寫要分別創建不同對象。相比之下RandomAccessFile類則可對文件實現隨機讀寫操作。
RandomAccessFile對象的文件位置指針遵循下面的規律:
·新建RandomAccessFile對象的文件位置指針位于文件的開頭處;
·每次讀寫操作之后,文件位置的指針都相應后移到讀寫的字節數;
·可以通過getFilePointer方法來獲得文件位置指針的位置,通過seek方法來設置文件指針的位置。
RandomAccessFile例子:
package net;
import java.io.*;
class RandomAccessFileDemo
{
????public static void main(String args[]) throws IOException
???? {
????????//以讀和寫的方式創建RandomAccessFile對象
???????? RandomAccessFile f=new RandomAccessFile("myfile","rw");
???????? System.out.println("File length:"+(f.length())+"B");
???????? System.out.println("File Pointer Position:"+f.getFilePointer());
???????//下面從文件末尾處開始寫數據
??????? f.seek(f.length());
??????? f.writeBoolean(true);
??????? f.writeBoolean(false);
??????? f.writeChar('a');
??????? f.writeChars("Hello!!");
??????? System.out.println("File length:"+(f.length())+"B");
???????//下面從文件起始處開始讀數據
??????? f.seek(0);
??????? System.out.println("kkk::"+f.readBoolean());
??????? System.out.println("kkk::"+f.readBoolean());
???????while(f.getFilePointer()<f.length())
??????? {
??????????? System.out.println(f.readLine());
??????? }
??????? f.close();
???? }
}
posted on 2007-07-16 22:53
jadmin 閱讀(92)
評論(0) 編輯 收藏